Quick Refresh of Python Basics
-
Refer this article to understand the basics of Python programming language in no time.
Useful for beginners to start with Python or to prepare for interviews or for those who are looking for a quick brush-up of Python basics.
Topics are explained with sample code snippets for better understanding. -
Contents
-
Python
Python is:
Cross platform - Works on Windows, Linux, mac, etc without additional setup
High level - Resembles natural language and mathematical notations
Interpreted - Executes command line by line without compilation. So less time to develop
Modular - Supports modularity by using the concepts of packages and modules
Provides extensive sets of standard and third-party libraries
Object oriented
Simple to learn
Can be used to develop console applications that can be scheduled, GUI applications, web applications, data science projects, machine learning solutions, etc.
-
Download and Install
Download latest version of python from Python Website.
Previous versions also can be downloaded from here. Install python by running the downloaded .exe file. Check for successful installation by opening command prompt and typing python --version
Output will be the current version of python like Python 3.10.0
-
Python Interpreter
Python interpreter helps writing python code in the command line itself.
To open python interpreter, type python.
Interpreter will become enabled with below message and >>> symbol.
Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>
We can write python code next to >>>
Code that needs multiple lines are denoted by ...
... automatically comes for multi-line commands like if, for.>>> age = 70 >>> if age < 18: ... print("Young") ... elif age >=18 and age < 60: ... print("Adult") ... else: ... print("Old") ... Old
To exit interpreter, type Ctrl+Z then Enter.
-
py.exe launcher
This launcher is used for Windows OS.
py.exe launcher can be used for executing code under different versions.
Type py to check if launcher is installed. Will display latest python version. Some sample usages below.For Windows.
py -3.3Executes code/module in python 3.3 version
py -3Executes in latest 3.x version available in your machine
For Linux, macOS, etc we can do this by using below commands and py launcher is not required.
python3.3Executes code/module in python 3.3 version
python3Executes in latest 3.x version available in your machine
-
Datatypes
Python uses variables to hold data. Data can be of different types. Python has 3 basic data types.
numericint, float, complex
textstr
booleanbool
Numeric types are:
intWhole numbers
floatDecimal numbers
complexComplex numbers represented as 10 + 2J used in advanced calculations
Same variables can be used for different datatypes. Below example works fine.
a= 10 a = "Test String"
-
Strings
String datatype is used to hold texts. String values should be placed within "". Strings can be manipulated using built-in functions.
Some examples below. Consider a string: s = " This is a string "Action Sample Output Slicing s[0:4] This Upper case s[0:4]. upper() THIS Trim spaces s.strip() This is a string Replace s[0:4]. replace ("h", "j") Tjis Split s.split (" ") ['This', 'is', 'a', 'string'] Concat "Concat " + "test" Concat test To combine string and non-string values, use string formatting as shown below.
num = 30 text = "Text is combined with number {}" print(text.format(num))
Output:
Text is combined with number 30Additional Links -
String Formatting
Easier way of combining multiple values. Uses {} as place holders. Within bracket we can provide name or index.
Format type option can be provided as second parameter.
Some common formats are decimal(:d), number(:n), percentage(:%). Number of decimal places to display can be indicated after :.
Examples below:s1 = "String with 2 values: {0} and {1}".format("One", 2) s2 = "String with 2 values: {first} and {second}".format(first ="One", second =2) print (s1) print (s2) marksPercent = "Marks Percent is {:.1%}" print(marksPercent.format(0.7522))
Output:
String with 2 values: One and 2
String with 2 values: One and 2
Marks Percent is 75.2%For more, click Python String Formatting.
-
Casting
Python provides built-in functions to convert data types. int(), float(), str()
Examples below:n1 = 10 #integer datatype n2 = 20.25 #floating datatype n3 = 20 + 5J #complex datatype print("Type of " + str(n1) + " is ", type(n1)) print("Type of " + str(n2) + " is ", type(n2)) print("Type of " + str(n3) + " is ", type(n3)) n1 = float(n1) n2 = int(n2) n3 = str(n3) print("After casting " + str(n1) + " is {0} type".format(type(n1))) print("After casting " + str(n2) + " is {0} type".format(type(n2))) print("After casting " + str(n3) + " is {0} type".format(type(n3)))
Output:
Type of 10 is <class 'int'>
Type of 20.25 is <class 'float'>
Type of (20+5j) is <class 'complex'>
After casting 10.0 is <class 'float'> type
After casting 20 is <class 'int'> type
After casting (20+5j) is <class 'str'> type -
Operators for numeric data types
Arithmetic operators are provided for performing all the basic arithmetic operations.
These are +, -, *, /, %, **, //
% is modulus operator which returns reminder of division
** is exponential operator (2 ** 3 = 2 * 2 * 2 = 8)
// is floor division. decimal part is skipped and integer value returnedAssignment operator is used to assign value to a variable.
a = 25
Comparison operators are used to compare 2 variables and return a Boolean result (True or False).
These are +, -, *, /, %, **, //
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
Logical operators are used to perform logical operations.
Samples below:n1 = 10 n2 = 5 n3 = 15 n4 = 15 print (n1 == n2 and n3 == n4)#'Both should be true to return True' print (n1 == n2 or n3 == n4)#'Atleast one should be true to return True' print(not(n3 == n4))#'If n3 is equal to n4 then False is returned'
Output:
False
True
False -
Python Dates
Date is not considered as a data type in python. To work with dates, we can import datetime package.
import datetime print(datetime.datetime.now()) print(datetime.datetime.now().year)
Output:
2021-11-18 10:53:14.024739
2021New date objects can be created like:
dt = datetime.datetime(2021, 3, 25)
Use strftime() to get parts of date in different formats.
print(dt.strftime("%m"))
Some options mentioned using above example:
%d - 25, %b - Mar, %B - March, %y - 21, %Y - 2021Additional Links -
Math Functions and Constants
Math functions can be applied on numeric datatypes.
Need to import Math module.
Important ones are:floor(), isfinite(), isnan(), pow(x, y), min(), max(), abs(), ceil()
.Some constants like math.pi, math.nan are also available.
-
Data Structures
Data structures are used to hold a collection of data into a single variable and manipulate these with associated built-in functions.
3 main groups are:sequencelist, tuple, range
mappingdict
setset, frozenset
A quick comparison:
listAllows duplicates. Multiple datatypes are allowed in a single list. Add or remove possible. Can change existing items. Represented by []
tupleAllows duplicates. Multiple datatypes allowed. Cannot add/remove/ modify items once created. Represented by ()
rangeMainly used to create a sequence between 2 ranges. Eg: rg = range(2,4) will have values 2 and 3
dictData stored as key-value pairs. Duplicate keys are not allowed. Add/remove items are permitted. Can modify existing values. Represented by {}
setDuplicates not allowed. Multiple datatypes allowed. Cannot change existing items. Can add or remove new items. Represented by {}
frozensetNo changes possible in frozen set
Samples:
listmyList = ["text1", 5, True, "Text2", "Text2"]
tuplemyTuple = ("text1", 5, True, "Text2", "Text2")
rangemyRange = range(3, 10)
dictmyDictionary = {"key1":"text1", "key2":5, "key3":True, "key4":"text2", "key1":"new text"}
setmySet = {"text1", 5, True, "Text2", "Text2"}
frozensetmyFrozenSet = frozenset(mySet)#'list, tuple, set can be frozen
-
Add/edit/delete data structures
Values of list, tuple and range can be accessed as index based. Dictionary is key based. Eg: myList[0] will display "text1". myDictionary["key1"] will display "text1". Sets can be looped. But index-based access is not possible.
For list and dictionary, we can change existing values as below. For other types it is not possible to change existing values. Eg: myList[0] = "new text" myDictionary["key1"] = "new text"
A common function len() is there to get the number of items for all data structures.
List has append(), insert(), remove(), pop() functions to add/remove items. Set has add(), remove() functions. For dictionary, to add item use myDictionary["newKey"] = "new text". For removing item from dictionary use pop().
Lists, tuples and sets can be joined together. List and tuples use + operator. Set uses union() function.
Data structures samples below:
print("#####Declare data structures#####") myList = ["text1", 5, True, "Text2", "Text2"] print(myList) myTuple = ("text1", 5, True, "Text2", "Text2") print(myTuple) myRange = range(3, 10) print(myRange[0], myRange[2]) myDictionary = {"key1":"text1", "key2":5, "key3":True, "key4":"text2", "key1":"new text"} print(myDictionary) mySet = {"text1", 5, True, "Text2", "Text2"} print(mySet) myFrozenSet = frozenset(mySet) print(myFrozenSet) print("#################################") print("#####Access, modify, add, remove data structures#####") print(myList[0], myTuple[0], myRange[0], myDictionary["key1"]) myList[0] = "new text" myDictionary["key1"] = "new text" print(myList) print(myDictionary) print(len(myList), len(myTuple), len(myRange), len(myDictionary), len(mySet)) myList.append("text at end") myList.insert(1, "text at second position") print(myList) myList.remove("text at end") myList.pop(2)#remove third item print(myList) print("#################################") print("#####Join lists, tuples and sets#####") secondList = [5, 6, True] secondTuple = (5, 6, True) secondSet = {5, 6, True} print("Joined List : {}".format(myList + secondList)) print("Joined Tuple : {}".format(myTuple + secondTuple)) print("Joined Set : {}".format(mySet.union(secondSet))) print("#################################")
-
List Comprehensions
List comprehensions are pythons short way of creating a new list from existing.
This allows to filter lists to create a new list with a single line of code.
Can be applied on any iterable. ie, Data structures or strings.
Following example filters out even numbers from an existing list and create a new list:num = [5, 10, 7, 25, 34, 15, 20, 38, 45, 50] even = [e for e in num if e%2 == 0] print(even)
Output:
[10, 34, 20, 38, 50] -
Python Comments
Single line comments. Use #
#This is a comment
Multi-line comments. Use """ ..... """ or ''' ..... '''
""" Comment line 1 Comment line 2 """
-
Python If
Python has option to do conditional checks using if---elif---else statements.
Boolean values are expected in the if---else conditions. ie, Comparison and logical operations can be used here as in example below.age = 15 if age < 18: print("Young") elif age >=18 and age < 60: print("Adult") else: print("Old")
Output:
Young -
Python Match
match...case is a different way of conditional flow. Use this feature to check for a particular value rather than a comparison or logical operation.
This is a new feature. Example below.count = 5 match count: case 1: print("I have 1 pen") case 2: print("I have 1 pens") case _: print("I have more than 3 pens")
Output:
Youngcase _: is the default case, if none of the above cases match.
-
Python For and While Loops
Python has 2 looping statements. while, for.
while is used if don't have a particular sequence and we want to loop till a particular condition is satisfied.
for is used to iterate through data structures or characters in a string.
Examples belowticks = 0 while ticks < 5: ticks = ticks + 1 print("Tick " + str(ticks))
Output:
Tick 1
Tick 2
Tick 3
Tick 4
Tick 5myList = ["text1", 5, True, "Text2", "Text2"] for l in myList: print(l)
Output:
text1
5
True
Text2
Text2 -
break, continue, pass
break is used to exit from loops.
continue is used to skip lines below and continue with next iteration.
pass can be used to declare an empty block. To do nothing for a particular action.if age < 1: pass
-
Functions
Functions are a set of actions that can be performed when called. Functions are defined using def keyword. Can have 0 or more parameters. Function can return any datatypes or data structures.
def findSum(a, b): return a+ b s = findSum(5, 2) print(s)
Output:
7If number of input args are expected to change, we an put a * symbol to indicate that and pass any number of args.
Example below:def findSum(*a): s = 0 for l in a: s = s + l return s s = findSum(5, 2, 3, 10) print(s)
Output:
20Python allows setting default values to a parameter and also keyword arguments.
-
Lambda
Lambda is a single lined anonymous function. Lambda functions can accept any number of arguments. Can be called using the variable name it is assigned to.
Syntax: lambda commaseparatedargs : operation
Example:sum = lambda a, b, c : a + b + c print(sum(10, 20, 50))
Output:
80 -
Classes and Objects
Classes can be considered as a template with a set of predefined properties and functions. Properties are variables that holds values. Functions are a set of actions that we do to get a desired outcome.
To use classes, we create objects from it. Objects are the instances of a class and any number of objects can be created from a class template. Objects can hold values for all the class properties and can call the class functions to do a particular type of action.
Sample Class:
Consider a school with lots of students. Each student will be having different name, date of birth, grade, etc. They will be studying different subjects.
It may be required to perform different action like calculate age based on date of birth, calculate marks, etc. So we can create a class template with name, dob as properties and calculateAge(), calculateMarks() as functions. This template can be used to represent all the students as objects.__init__() is the first method that is getting called on creating an object and it is mandatory for all classes. This can be used to initialize the variables.
Values can be assigned at the time of creating object, which uses __init__() method or by calling objectName.property. Similarly, functions are called as objectName.functionName().
Sample code below:
import datetime class Student: def __init__(self, name, dob, gender, grade): self.name = name self.dob = dob self.gender = gender self.grade = grade self.subjects = ["Maths"] def calculateAge(self): d = datetime.datetime.today() years = d.year - self.dob.year - ((d.month, d.day) < (self.dob.month, self.dob.day)) return years def calculateMarks(self): marks = 100 #Do some action here return marks student1 = Student("John", datetime.date(2005,10, 22), "M", 10) print("Age of {} is {}".format(student1.name, student1.calculateAge())) student1.subjects.append("Chemistry") print("{} studies {}".format(student1.name, student1.subjects)) student2 = Student("Tom", datetime.date(2007,5, 15), "M", 8) print("Age of {} is {}".format(student2.name, student2.calculateAge())) student2.subjects.remove("Maths") student2.subjects.append("History") print("{} studies {}".format(student2.name, student2.subjects))
Age of John is 16
John studies ['Maths', 'Chemistry']
Age of Tom is 14
Tom studies ['History']
-
Inheritance
Python supports inheritance. Parent class features can be assessed to child class by inheriting.
class Parent: def __init__(self): print("Parent Constructor") def parentFunc(self): print("Parent Function") class Child(Parent): def __init__(self): print("Child Constructor") super().__init__() def childFunc(self): print("Child Function") c = Child() c.parentFunc()
Output:
Child Constructor
Parent Constructor
Parent FunctionAs in above sample, child objects can access parent functions and properties.
Python supports multiple and multilevel inheritance.
super() function can be used to access parent functions and variables from child class. -
Error handling
Error handling blocks are as below
try: #Some code here except: #exception block here else: #steps to execute if no error occurs finally: #executes regardless of error or not
-
Scopes
LocalVariables created and used within function are accessible within function only. This is local scope.
GlobalVariables created in the main body. Accessible throughout the module. Also, in imported modules.
Same variable name is possible as global and local within the same module.
To access a global variable from within a function, use keyword global. -
Iterators
Iterators are objects that can be looped using for statement.
Data structures and string datatype are iterable using for loop, which will access each element at a time, in case of string each character.
Iterable objects implements iterator, that has functions iter() and __next__()
iter() returns a loopable object in back-end.
__next__() access one element at a time till end. After that StopIteration() exception is raised.
When using for loop, these steps happen in behind the scenes and we need not worry about these while implementing. -
Generator
A normal function returns the result as a single unit. It can return any basic data type or a data structure such as list.
A generator is also a kind of function. Difference is that generator return a single item of a loopable object (strings or data structures) at a time.
Advantage of generator over a function is that generators are iterable and we can use it directly in a for loop.
Generators can be implemented using yield keyword.
See example below which calculates sum till the entered number.def sumTill(num): i = 0 j = 0 for n in range(num): j += 1 i = i + j if (j > num): break yield "Sum of numbers from 0 to {0} = {1}".format(j, i); for n in sumTill(5): print (n)
Output:
Sum of numbers from 0 to 1 = 1
Sum of numbers from 0 to 2 = 3
Sum of numbers from 0 to 3 = 6
Sum of numbers from 0 to 4 = 10
Sum of numbers from 0 to 5 = 15
-
Standard Libraries
Python comes with a set of standard packages which we can you in our modules just by importing them. For example, datetime module helps us to work with dates easily. These packages come with the python installation, and we don't have to install them separately. Some of the most important and most used built-in packages are:
Lib Description Major Functions/ Properties os To interact with operating system dir - List of modules
getcwd - Current working directoryshutil Directory management like copy, move copyfile - Copy files from one location to another
move - Move files from one location to anothersys Python runtime operations argv - To get arguments passed
path - Path of all python modules
version - Python versionre Regular Expressions findall - Find all matching
replace - Replace content with newmath Math operations floor - Returns integer value
lcm - Least common multiple of specified integersrandom Random operations choice - Selects random value from a list
random - Random number between 0 and 1urllib. request Retrieve data from urls urlopen smtplib Mail sending sendmail datetime Date operations strftime - Get date in different format
date - Create new date objectzlib Data compress/ decompress compress - Compress files
decompress - Decompress filesthreading Multi-threading functions Thread - Start thread logging Log functions debug - Debug messages
warning - Warning messages
error - Error messages -
Third Party Libraries
Third party libraries are the modules/packages developed by other users that can be used in our modules.
First, we need to install these using the command pip install <Packagename>
Then we can use its functionalities by importing it to our modules. -
Modules
Modules can be considered as a group of statements kept together in a single file. As our programs become larger, keeping similar sections as a module helps in better organizing the code. It helps in re-usability as well.
In python module is usually a single file saved as .py
Below example shows how to create module and add some functions to it and reuse it in a different module.
Create a file named myModule.py and add below code. As seen here, it has 2 functions.def myFunc1(): print("This is myFunc1() of myModule") def myFunc2(val): print("This is myFunc2() of myModule with input {}".format(val))
One function has empty parameters and the other has one input parameter.
Now create a new file testMyModule.py in the same folder and add below code.import myModule myModule.myFunc1() myModule.myFunc2(1) myModule.myFunc2("test")
Running the test module will get you the below output.
Output:
This is myFunc1() of myModule
This is myFunc2() of myModule with input 1
This is myFunc2() of myModule with input test
It is important to note that the module that you create should be within same folder of the file that you are using it. Or we can place our modules in the folder mentioned in the sys.path environment variable.
-
Packages
Packages can be considered as a collection of modules. A package can contain multiple folders inside, each containing multiple modules.
We can import the entire package to a new module by using command: import <packageName>
Or a particular module only within the package using: import <packageName>.<moduleName>
Packages should be placed in the same folder or in the sys.path. -
Install, update remove packages
All the open source and licensed packages are listed in Python Package Index repository. We can use the pip command to install a package which is available in this repository.
To install python -m pip install PackageName
For specific version python -m pip install PackageName==3.0.2
For min version python -m pip install PackageName>=3.0.2
For upgrade python -m pip install -upgrade PackageName
To use older python versions:For Windows:py -3.3 -m pip install PackageNamefor python 3.3 versionpy -3 -m pip install PackageNamefor latest 3.x version available in your machineFor Linux, macOS, etc:python3.3 -m pip install PackageNamefor python 3.3 versionpython3 -m pip install PackageNamefor latest 3.x version available in your machine -
Files
Python has built-in functions to work with some type of files like .txt. For other types we can use third-party libraries like python-docx for word documents or openpyxl for excel worksheets.
To open:f = open("TestFile.txt", "r")Second parameter is mode. Modes are r - read, w - write, a - append, x - createTo read:f.read()Reads all linesf.read(10)Reads first 10 charactersf.readline()Reads 1 line. Call this multiple times to read next lines.for l in f print(l)To loop through all linesTo Write:f.write("Content")Open file in w or a mode and writeTo Delete:os.remove("TestFile.txt")File delete functions are available in os module. Import it for file deleteClose:close()Make sure to close file after read or write. -
Input/Output
To get user input from console use input() function.
To display result, use print()age = input("Enter Age : ") print(age)
Output:
Enter Age : 30
30 -
Json
Python has json standard library to work with json strings. It provides mainly 2 methods.
To read from json use loads().import json jsonStr = '{"employees" : [{"name" : "Tim", "role" : "CEO"}, {"name" : "Tiffany", "role" : "Manager"}, {"name" : "Eric", "role" : "Associate"}]}' jsn = json.loads(jsonStr) print(len(jsn["employees"])) print(jsn["employees"][0]["name"])
Output:
3
TimTo convert objects to json use dumps().
lst = ["Car", "Bus", "Bike", 1, 2, True] a = json.dumps(lst) print (a)
Output:
["Car", "Bus", "Bike", 1, 2, true]Data types strings, int, float, bool and data structures list, tuple, dict are serializable.
Complex numbers cannot be serialized. So is set data structure. -
Virtual environments
When we install a package for our project, it gets copied to site_packages folder mentioned in pythonpath. When we work with multiple projects, there may be scenarios that require different versions of a third-party package for these projects. While installing a package, there are chances that older version gets uninstalled and may be some other conflicts that can occur. This may result in one or more of your projects to stop working. This is where virtual environment becomes useful.
python -m venv <ProjectName>
Virtual environments can be considered as a separate directory where all your project related files are stored and not depend on the common python installation locations.
To create virtual environment: Navigate to the folder from comment prompt and type:
This command will create some folders like Include, Lib, Scripts and varies depending on OS. All our pip installations will be kept in Lib/site-packages folder. Scripts folder has activate.bat file.
Next step is to activate the VE using command:Windows:ProjectName\Scripts\activate.batLinux/MacOS:source ProjectName /bin/activateNow we can execute all python commands in this virtual environments like installing package, running a module, etc.
pip not found error in virtual environment
In some cases, when we try to install packages in virtual environments using pip commands, we will get an error like: pip not found.
To fix this, run the below command:
python -m ensurepipSetting up virtual environment for older python versions
Some of the packages may not be working in latest version of Python. If so, we have to setup everything for older python version, including virtual environment. Use the below commands. This sample sets up Python 3.9 virtual environment.
Windows:py -3.9 -m venv <ProjectName>Linux/MacOS:python3.9 -m venv <ProjectName>After setting this up, we can install additional packages to this virtual environment using command pip3.9 install <Package Name> or pip install <Package Name> -
Sys.path and Pythonpath
Sys.path are the folder locations that python will search for, for the installed packages when a project runs. Our referenced packages should be available in any of these paths in order for our projects to run. Run below command in interpreter to see the paths.
import sys sys.path ['', 'C:\\Users\\<UserName>\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\<UserName>\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\<UserName>\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\<UserName>\\AppData\\Local\\Programs\\Python\\Python310', 'C:\\Users\\<UserName>\\AppData\\Roaming\\Python\\Python310\\site-packages']
Pythonpath is an environment variable that we can set to add additional paths for our projects, which can contain python modules that we use in our project.