Python has ranked first multiple times in the popularity index PYPL for programming languages.
Due to its code readability and simpler syntax, it is considered one of the easiest languages ever.
The richness of various AI and machine learning libraries such as NumPy, Pandas, and TensorFlow is one of the core demands of Python.
If you are a data scientist or a beginner in AI/machine learning, Python is the right choice to start your journey.
In this article, I will explore some fundamental knowledge of Python programming with you. Although simple, they are very useful.
-
Table of Contents
-
Data Types
-
Variables
-
Lists
-
Sets
-
Dictionaries
-
Comments
-
Basic Functions
-
Conditional Statements
-
Loop Statements
-
Functions
-
Exception Handling
-
String Operations
-
Regular Expressions
▍1. Data Types
Data types are specifications of data that can be stored in variables. The interpreter allocates memory for variables based on their types.
Here are the various data types in Python.

▍2. Variables
Variables are containers for storing data values.
Variables can use short names (like x and y) or more descriptive names (age, carname, total_volume).
Python variable naming rules:
-
Variable names must start with a letter or underscore character
-
Variable names cannot start with a number
-
Variable names can only contain alphanumeric characters and underscores (A-z, 0-9, and _)
-
Variable names are case-sensitive (age, Age, and AGE are three different variables)
var1 = 'Hello World'
var2 = 16
_unuseful = 'Single use variables'
The output is as follows.

▍3. Lists
Lists are an ordered and mutable collection that allows duplicate members.
They can be heterogeneous, and we can create a list containing different data types (such as integers, strings, and objects).
>>> companies = ["apple","google","tcs","accenture"]
>>> print(companies)
['apple', 'google', 'tcs', 'accenture']
>>> companies.append("infosys")
>>> print(companies)
['apple', 'google', 'tcs', 'accenture', 'infosys']
>>> print(len(companies))
5
>>> print(companies[2])
tcs
>>> print(companies[-2])
accenture
>>> print(companies[1:])
['google', 'tcs', 'accenture', 'infosys']
>>> print(companies[:1])
['apple']
>>> print(companies[1:3])
['google', 'tcs']
>>> companies.remove("infosys")
>>> print(companies)
["apple","google","tcs","accenture"]
>>> companies.pop()
>>> print(companies)
["apple","google","tcs"]
▍4. Sets
Sets are an unordered and unindexed collection with no duplicate members.
They are very useful for removing duplicate entries from lists. They also support various mathematical operations such as union, intersection, and difference.
>>> set1 = {1,2,3,7,8,9,3,8,1}
>>> print(set1)
{1, 2, 3, 7, 8, 9}
>>> set1.add(5)
>>> set1.remove(9)
>>> print(set1)
{1, 2, 3, 5, 7, 8}
>>> set2 = {1,2,6,4,2}
>>> print(set2)
{1, 2, 4, 6}
>>> print(set1.union(set2)) # set1 | set2
{1, 2, 3, 4, 5, 6, 7, 8}
>>> print(set1.intersection(set2)) # set1 & set2
{1, 2}
>>> print(set1.difference(set2)) # set1 - set2
{8, 3, 5, 7}
>>> print(set2.difference(set1)) # set2 - set1
{4, 6}
▍5. Dictionaries
Dictionaries are mutable unordered collections of key-value pairs.
Unlike other data types, they store data in the format of {key: value} pairs instead of storing single data. This feature makes them the best data structure for mapping JSON responses.
>>> # example 1
>>> user = { 'username': 'Fan', 'age': 20, 'mail_id': '[email protected]', 'phone': '18650886088' }
>>> print(user)
{'mail_id': '[email protected]', 'age': 20, 'username': 'Fan', 'phone': '18650886088'}
>>> print(user['age'])
20
>>> for key in user.keys():
>>> print(key)
mail_id
age
username
phone
>>> for value in user.values():
>>> print(value)
[email protected]
20
Fan
18650886088
>>> for item in user.items():
>>> print(item)
('mail_id', '[email protected]')
('age', 20)
('username', 'Fan')
('phone', '18650886088')
>>> # example 2
>>> user = {
>>> 'username': "Fan",
>>> 'social_media': [
>>> {
>>> 'name': "Linkedin",
>>> 'url': "https://www.linkedin.com/in/codemaker2022"
>>> },
>>> {
>>> 'name': "Github",
>>> 'url': "https://github.com/codemaker2022"
>>> },
>>> {
>>> 'name': "QQ",
>>> 'url': "https://codemaker2022.qq.com"
>>> }
>>> ],
>>> 'contact': [
>>> {
>>> 'mail': [
>>> "[email protected]",
>>> "[email protected]"
>>> ],
>>> 'phone': "18650886088"
>>> }
>>> ]
>>> }
>>> print(user)
{'username': 'Fan', 'social_media': [{'url': 'https://www.linkedin.com/in/codemaker2022', 'name': 'Linkedin'}, {'url': 'https://github.com/codemaker2022', 'name': 'Github'}, {'url': 'https://codemaker2022.qq.com', 'name': 'QQ'}], 'contact': [{'phone': '18650886088', 'mail': ['[email protected]', '[email protected]']}]}
>>> print(user['social_media'][0]['url'])
https://www.linkedin.com/in/codemaker2022
>>> print(user['contact'])
[{'phone': '18650886088', 'mail': ['[email protected]', '[email protected]']}]
▍6. Comments
Single-line comments start with a hash character (#) and end with a message at the end of the line.
# Define user age
age = 27
dob = '16/12/1994' # Define user birthday
Multi-line comments are enclosed in special quotes (“””), allowing you to place messages over multiple lines.
"""
Python Tips
This is a multi line comment
"""
▍7. Basic Functions
The print() function prints the provided message to the console. You can also provide file or buffer input as parameters to print on the screen.
print(object(s), sep=separator, end=end, file=file, flush=flush)
print("Hello World") # prints Hello World
print("Hello", "World") # prints Hello World?
x = ("AA", "BB", "CC")
print(x) # prints ('AA', 'BB', 'CC')
print("Hello", "World", sep="---") # prints Hello---World
The input() function is used to collect user input from the console.
Note that input() converts whatever you enter into a string.
Thus, if you provide age as an integer, the input() method will return it as a string, and you need to manually convert it back to an integer.
>>> name = input("Enter your name: ")
Enter your name: Codemaker
>>> print("Hello", name)
Hello Codemaker
The len() function can check the length of an object. If you input a string, you can get the number of characters in that string.
>>> str1 = "Hello World"
>>> print("The length of the string is ", len(str1))
The length of the string is 11
str() is used to convert other data types to string values.
>>> str(123)
123
>>> str(3.14)
3.14
int() is used to convert strings to integers.
>>> int("123")
123
>>> int(3.14)
3
▍8. Conditional Statements
Conditional statements are code blocks used to change the program flow based on specific conditions. These statements will only execute if certain conditions are met.
In Python, we use if, if-else, and loops (for, while) as conditional statements to alter the program flow based on certain conditions.
if-else statements.
>>> num = 5
>>> if (num > 0):
>>> print("Positive integer")
>>> else:
>>> print("Negative integer")
elif statements.
>>> name = 'admin'
>>> if name == 'User1':
>>> print('Only read access')
>>> elif name == 'admin':
>>> print('Having read and write access')
>>> else:
>>> print('Invalid user')
Having read and write access
▍9. Loop Statements
Loops are conditional statements used to repeat certain statements (in their body) until a condition is met.
In Python, we commonly use for and while loops.
for loops.
>>> # loop through a list
>>> companies = ["apple", "google", "tcs"]
>>> for x in companies:
>>> print(x)
apple
google
tcs
>>> # loop through string
>>> for x in "TCS":
>>> print(x)
T
C
S
The range() function returns a sequence of numbers, which can be used to control for loops.
It basically requires three parameters, of which the second and third are optional. The parameters are start value, stop value, and step count. The step count is the increment value of the loop variable on each iteration.
>>> # loop with range() function
>>> for x in range(5):
>>> print(x)
0
1
2
3
4
>>> for x in range(2, 5):
>>> print(x)
2
3
4
>>> for x in range(2, 10, 3):
>>> print(x)
2
5
8
We can also use the else keyword to execute some statements at the end of the loop.
Provide an else statement at the end of the loop along with the statements that need to be executed when the loop ends.
>>> for x in range(5):
>>> print(x)
>>> else:
>>> print("finished")
0
1
2
3
4
finished
while loops.
>>> count = 0
>>> while (count < 5):
>>> print(count)
>>> count = count + 1
0
1
2
3
4
We can use else at the end of a while loop, similar to a for loop, to execute some statements when the condition is false.
>>> count = 0
>>> while (count < 5):
>>> print(count)
>>> count = count + 1
>>> else:
>>> print("Count is greater than 4")
0
1
2
3
4
Count is greater than 4
▍10. Functions
Functions are reusable code blocks used to perform tasks. They are very useful for modularizing code and making it reusable.
>>> # This prints a passed string into this function
>>> def display(str):
>>> print(str)
>>> return
>>> display("Hello World")
Hello World
▍11. Exception Handling
Even if statements are syntactically correct, errors may occur during execution. These types of errors are called exceptions. We can use the exception handling mechanism to avoid such problems.
In Python, we implement exception handling in the code using the try, except, and finally keywords.
>>> def divider(num1, num2):
>>> try:
>>> return num1 / num2
>>> except ZeroDivisionError as e:
>>> print('Error: Invalid argument: {}'.format(e))
>>> finally:
>>> print("finished")
>>>
>>> print(divider(2,1))
>>> print(divider(2,0))
finished
2.0
Error: Invalid argument: division by zero
finished
None
▍12. String Operations
Strings are collections of characters enclosed in single or double quotes (‘, “).
We can perform various operations on strings using built-in methods, such as concatenation, slicing, trimming, reversing, case changes, and formatting, like split(), lower(), upper(), endswith(), join(), and ljust(), rjust(), format().
>>> msg = 'Hello World'
>>> print(msg)
Hello World
>>> print(msg[1])
e
>>> print(msg[-1])
d
>>> print(msg[:1])
H
>>> print(msg[1:])
ello World
>>> print(msg[:-1])
Hello Worl
>>> print(msg[::-1])
dlroW olleH
>>> print(msg[1:5])
ello
>>> print(msg.upper())
HELLO WORLD
>>> print(msg.lower())
hello world
>>> print(msg.startswith('Hello'))
True
>>> print(msg.endswith('World'))
True
>>> print(', '.join(['Hello', 'World', '2022']))
Hello, World, 2022
>>> print(' '.join(['Hello', 'World', '2022']))
Hello World 2022
>>> print("Hello World 2022".split())
['Hello', 'World', '2022']
>>> print("Hello World 2022".rjust(25, '-'))
---------Hello World 2022
>>> print("Hello World 2022".ljust(25, '*'))
Hello World 2022*********
>>> print("Hello World 2022".center(25, '#'))
#####Hello World 2022####
>>> name = "Codemaker"
>>> print("Hello %s" % name)
Hello Codemaker
>>> print("Hello {}".format(name))
Hello Codemaker
>>> print("Hello {0}{1}".format(name, "2022"))
Hello Codemaker2022
▍13. Regular Expressions
-
Import the regex module, import re.
-
Use the re.compile() function to create a Regex object.
-
Pass the search string to the search() method.
-
Call the group() method to return the matched text.
>>> import re
>>> phone_num_regex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
>>> mob = phone_num_regex.search('My number is 996-190-7453.')
>>> print('Phone number found: {}'.format(mob.group()))
Phone number found: 996-190-7453
>>> phone_num_regex = re.compile(r'^\d+$')
>>> is_valid = phone_num_regex.search('+919961907453.') is None
>>> print(is_valid)
True
>>> at_regex = re.compile(r'.at')
>>> strs = at_regex.findall('The cat in the hat sat on the mat.')
>>> print(strs)
['cat', 'hat', 'sat', 'mat']
That’s it for this session. Interested friends can practice and learn on their own.
——– End ——–

Featured Content
-
Illustrated Pandas – Figure 01 – Introduction to Data Structures -
Illustrated Pandas – Figure 02 – Creating Data Objects -
Illustrated Pandas – Figure 03 – Reading and Storing Excel Files -
Illustrated Pandas – Figure 04 – Common Data Access -
Illustrated Pandas – Figure 05 – Common Data Operations -
Illustrated Pandas – Figure 06 – Common Mathematical Calculations -
Illustrated Pandas – Figure 07 – Common Data Statistics -
Illustrated Pandas – Figure 08 – Common Data Filtering

