Python is a general purpose, high level, and interpreted programming language.
It supports Object Oriented
programming approach to develop applications.
Applications
It is used in web development.
Software development.
Mathematics.
System scripting.
Automation testing.
Advantages of Python
Python works on different platforms windows, Mac, Linux, Raspberry pi.
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write code in fewer lines compared to other
programming languages.
Python is open source and easily portable.
Python has massive library and easy to integrate.
Statement - A statement is an instruction that a Python interpreter can execute. Anything
written in Python is a statement.
Comments – It describes what is happening inside a program. Types of comments are –
Single - line comment
Multi – line comment
Add sensible comment
Inline comment
Block comment
Docstring comment
Keywords - Python keywords are reserved words that have a special meaning associated
with them and can’t be used for anything but those specific purposes.
Escape Sequence - An escape sequence is a sequence of characters that, when used inside a character or string, does
not represent itself but is converted into another character .
Escape Sequence Meaning
\’ Single quote
\” Double quote
\\ Backslash
\n Newline
\t Tab
\b Back space
Program 1
# ********** Print the following **********
# This is \\ double backslash
# This are /\/\/\/\/\ mountains
# The book is awesome (use escape sequence)
# \" \n \t \' print this as an output
Variables - A variable is a reserved memory area (memory address) to store value.
• Rules for naming a variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
A variable name cannot be any of the Python keywords.
• Multi Words Variable Names
Camel Case - Each word, except the first, starts with a capital letter eg: myVariableName = "John"
Pascal Case - Each word starts with a capital letter eg: MyVariableName = "John"
Snake Case - Each word is separated by an underscore character eg: my_variable_name = "John"
Python as Calculator
Operator Description Example
+ Addition 2+3=5
- Subtraction 2 - 3 = -1
* Multiplication 2*3=6
/ Float Division 4 / 2 = 2.0
// Integer Division 4 // 2 = 2
% Modulo 6%2=0
** Exponent 2 ** 3 = 8
Program 2 - Python as Calculator
Precedence Rule
Program 3 – Precedence rule
print(round(2 ** 0.5,5)) Sqrt of 2 up to 5 decimal place
print(2 ** 3 ** 2) a = 20
L b = 10
R
c = 15
d=5
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print ("Value of (a + b) * c / d is ", e) # 90.0
e = ((a + b) * c) / d # (30 * 15 ) / 5
print ("Value of ((a + b) * c) / d is ", e) # 90.0
e = (a + b) * (c / d); # (30) * (15/5)
print ("Value of (a + b) * (c / d) is ", e) # 90.0
e = a + (b * c) / d; # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e) # 50.0
Python Data types - Data types specify the different sizes and values that can be stored in the variable.
Type Casting – Converting variables declared in specific data type to the different data type is called
type casting.
Python performs two types of casting
• Implicit – The python interpreter automatically performs an implicit type conversion, which avoids loss
of data.
• Explicit – The explicit type conversion is performed by the user, using built – in function.
• To do type casting following built – in function are used.
Int – Convert any type variable to the integer type.
Float – Convert any type variable to the float type.
Complex – Convert any type variable to the complex type.
Bool – Convert any type variable to the bool type.
Str – Convert any type variable to the string type.
Program 4
# Converting float data type to integer data type
pi = 3.14
print(pi)
print(type(pi))
num = int(pi)
print(num)
print(type(num))
# Integer to float data type
num = 314
print(num)
print(type(num))
num1 = float(num)
print(num1)
print(type(num1))
Python allows you to assign values to multiple variables in one line
x, y, z = "Orange", "Banana", "Cherry"
print(x) = Orange
print(y) = Banana
print(z) = Cherry
# Assigning same value to multiple variable
x=y=z = "Orange"
print("The value of x:",x)
print("The value of y: “,y)
print("The value of z:",z)
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows to extract the values into variables. This is
called unpacking.
# Unpacking a collection
fruits = ["apple", "banana", "cherry"] # Unpacking a list
x, y, z = fruits
print(x)
print(y)
print(z)
Output Variables - The python print() function is used to output variables
Print() function outputs multiple variables using ‘+’ operator or ,
Operators - Operators are used to perform operations on variables and values.
Assignment Operators - Assignment operators are used to assign values to variables:
Comparison Operators - Comparison operators are used to compare two values:
Boolean Operator – Represents one of two values either True or False
Comparing two values, the expression is evaluated and Python returns the Boolean answer.
The bool() function allows to evaluate any value, and gives True or False in return.
There are not many values that evaluate to False, except empty values, such as (), [ ], { }, “ “, the number 0,
and the value none, and the false value evaluates to False.
Logical Operators - Logical operators are used to combine conditional statements:
Identity Operators - Identity operators are used to compare the objects, not if they
are equal, but if they are actually the same object, with the
same memory location.
Membership Operators – It is used to check if a sequence is present in an object.
Bitwise Operators – Bitwise operators are used to compare binary numbers
Bitwise & - It performs logical AND operation on the integer value after converting an integer to a binary value
and gives the result as a decimal value. It returns True only if both operands are True. Otherwise
False.
Bitwise | - It performs logical OR operation on the integer value after converting an integer to a binary value
and gives the result as a decimal value. It returns False if one of the operand is False/ True.
Otherwise True.
Bitwise xor ^ - It performs logical XOR operation on the integer value after converting an integer to a binary
value and gives the result as a decimal value.
~ Not – Inverts all the bits
Bitwise 1’s complement - It performs 1’s complement operation. It invert each bit of binary value and returns the
bitwise negation of a value as a result.
Bitwise left – shift << - It shifts the bit by a given number of place towards left and fill’s zeros to new position.
Bitwise right – shift >> - It shifts the bit by a given number of place towards right and here some bits are lost.
Python Control Flow
Flow control is the order in which statements or blocks of code are
executed at runtime based on a condition.
If – Statement - The if statement is the simplest form. It takes a condition and evaluates to
either True or False.
Syntax : Flow chart of if statement :
Pass Statement – if – statement cannot be empty, if if-statement is
empty it shows an error, to avoid the error Pass
statement is used.
If – else statement - The if-else statement checks the condition and executes the if block of code when the
condition is True, and if the condition is False, it will execute the else block of code.
Syntax : Flow chart of if statement
If – elif - else statement - The if-elif - else condition statement has an elif blocks to chain multiple conditions
one after another. The elif statement checks multiple conditions one by one and if
the condition fulfills, then executes that code.
Syntax
Nested – if statement - The nested if – else statement is an if statement inside another if – else statement.
Indentation is the only way to differentiate the level of nesting.
Syntax :
For loop - A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
Syntax :
for variable in iterable:
statement
Range Function and For Loop in Python
The range() function is commonly used for for loops in Python. It creates a sequence of numbers that help determine
the number of times the loop iterates. The three arguments for the range() function are as follows:
Start
Stop
Step
Break and Continue statement
Note - The else block will not be executed if the loop is stopped by a break statement.
While Loop in Python – The while loop is an entry controlled loop, and for loop is a count controlled loop.
Syntax :
while condition:
statement
While statement is used for infinite number of iteration.
For statement is used for finite number of iteration.
Lists
Lists are used to store multiple values in a single variable.
Lists are one of the 4 built – in datatype in Python.
Lists are created using [ ].
Lists are ordered, changeable, allows duplicate value, heterogeneous.
Lists are created using two ways:
Using list( ) constructor – Created a list by passing the , separated values inside the [ ].
Using [ ] – Create a list simply by enclosing the items inside the square bracket.
Length of the list – It is determined by using len()
Access list items
Indexing
Negative indexing
Range of indexing / negative
Using in keyword
Change list items
Change a single item value
Change a range of item values
Syntax
Add list items
Append Variable [Link](value), it takes exactly one argument
Insert Variable [Link](position, value), it takes two arguments
Extend Variable [Link](variable name2)
To append elements from another list to the current list
Remove list items
Remove Variable [Link](“value”)
Remove specified position Variable [Link](position)
Del del variable name[ ]
Clear
If position not given,
Index value Removes the last item
If index value not
It empties the list
given deletes the
entire list Syntax : del variable name
Variable [Link]( )
Loop list – Using for( ) and while( ) loop, we can loop through the list using range( ) & len( ) function
Looping Using List Comprehension
List Comprehension offers the shortest syntax for looping through lists:
Syntax :
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [expression for item in iterable if condition == True]
newlist = [x for x in fruits if "a" in x] The condition is like a filter that only accepts the items that valuate
to True
Python - Sort Lists
A sort( ) method will sort the list alphanumerically, ascending by default.
Variable [Link]( ) Ascending order
Variable [Link](reverse = True)
Reverse() – This method reverses the current sorting order of the elements.
Syntax
Python copy list
Using copy( ) method newlist = variable [Link]()
Using list( ) method newlist = list(variable name)
Python join list
Concatenation ‘ + ‘ = Variable 1 + Variable 2
Append() = It uses for loop
Extend() = variable [Link](variable 2)
Tuple
Tuples are used to store multiple values in a single variable.
Tuples are one of the 4 built – in datatype in Python.
Tuples are created using ( ).
Tuples are ordered, unchangeable, allows duplicate value, heterogeneous.
Tuples are created using two ways:
Using tuple( ) constructor – Creating a tuple by passing the , separated values inside the ().
Using () – Create a tuple simply by enclosing the items inside the () bracket.
Length of the tuple – It is determined by using len()
Access tuple items
Indexing
Negative indexing
Range of indexing / negative
Using in keyword
Update a Tuple: Tuples cannot be changed as they are immutable, by converting a tuple to list the values
can be changed.
Add tuple items
Replace
Append
Adding to tuples
Remove tuple items Convert tuple to list and use remove() method,
Variable [Link](“Value”)
Unpacking a tuple
In Python, the values can be extracted back into the variables. This is called "unpacking"
Note: The number of variables must match the number of values in the tuple, if not, you must use an asterisk to
collect the remaining values as a list.
If the number of variables is less than the number of values, add an * to the variable name and the values
will be assigned to the variable as a list.
Loop tuple – Using for( ) and while( ) loop, we can loop through the tuple using range( ) & len( ) function
Join tuple – To join one or more tuple use “+” operator.
To multiply a tuple given number of times use “*” operator.
Tuple copy - Create a copy of a tuple using the assignment operator “ = “. This operation will create
only a reference copy and not a deep copy because tuples are immutable.
Sets
Sets are used to store multiple values in a single variable.
Sets are one of the 4 built – in datatype in Python.
Sets are created using { }.
Sets are unordered, unchangeable, does not allow duplicate value, heterogeneous.
Sets are created using two ways:
Using set{} constructor – Created a list by passing the , separated values inside the { }.
Using () – Create a set simply by enclosing the items inside the { } bracket.
Length of the set – It is determined by using len()
Access set items
Cannot access a set item using index number.
Once a set is created, items cannot be changed, but new items can be
added.
Add set items
To add items from another set into the current set, use the update() method.
The object in the update() method does not have to be a set, it can be any iterable object
(tuples, lists, dictionaries etc.).
Remove set items
Remove Variable [Link](“value”)
Discard Variable [Link](value)
Del del variable name Syntax : del variable name
Clear It empties the set Variable [Link]( )
Pop It removes an item randomly. Variable [Link]()
Loop Set – Using for( ) and while( ) loop, we can loop through the list using range( ) & len( ) function
set1 = {"apple", "banana", "cherry"}
for x in set1:
print(x)
Dictionaries - Dictionaries are used to store data values in key:value pairs.
Dictionaries are written with curly brackets, and have keys and values.
Dictionary items are ordered, changeable, and do not allow duplicates.
Dictionaries cannot have two items with the same key.
Dictionary can be constructed also using dict( ) constructor.
Access dictionary items
Dictionary item can be accessed by using keys() and get().
Dictionary item can be accessed by using values().
Dictionary items can be accessed by using item() .
Change dictionary items
Change the value of a specific item by referring to its key name.
The update() method will update the dictionary with the items from the given
argument.
The argument must be a dictionary, or an iterable object with key:value pairs.
Add dictionary items
Adding an item to the dictionary is done by using a new index key and assigning a value to it.
Syntax : Variable name[“Key name”] = “Value”
The update() method will update the dictionary with the items from a given argument. If the
item does not exist, the item will be added.
Syntax : Variable [Link]({“Key name": “Value"})
Remove dictionary items The pop() method removes the item with the specified key name
Pop Syntax : variable [Link](“Key name”)
Popitem The popitem() method removes the last inserted item.
Syntax : variable [Link]()
Del del variable name Syntax : del variable name
del variable name[“Key name”]
Clear
The del keyword removes the item with the specified key name
It empties the dictionary
Variable [Link]( )
It removes an item randomly. Variable [Link]()
Loop dictionary – Using for( ) loop, when looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well.
Print all key names in the dictionary, one by one. Syntax : for i in variable name
print(i)
Print all values in the dictionary, one by one.
Syntax : for i in variable name:
print(variable name[i])
The values() method to return values of a dictionary: Syntax : for x in variable [Link]():
print(x)
The keys() method to return keys of a dictionary:
Syntax : for x in variable [Link]():
print(x)
Loop through both key and value using item () method
Syntax : for x , y in variable [Link]()
print(x , y)
Copy a Dictionary
Cannot copy a dictionary simply by typing dict2 = dict1, dict2 will only be a reference to dict1, and changes made in dict1 will
automatically also be made in dict2.
Copy() method dict() function
VN2 = [Link]() VN2 = dict(VN1)
Dictionary Unpack
Unpack any number of dictionary and add their contents to another dictionary using **kwargs. In this way, we can add
multiple length arguments to one dictionary in a single statement.
Syntax : New Variable name = {**Variable name1, **Variable name2, **Variable name3,…………}