PYTHON PORGRAMMING
([Link] BCC- 302)
Course Details Prof. SHIV VEER SINGH
([Link]-2nd Year, 3rd Sem.) Department of CSE-(IoT)
10/10/2023 Prof. SHIV VEER SINGH 1
What is Python Language?
• Python is a high-level general-purpose, interpreted, interactive,
object-oriented and reliable language having wide range of
applications from Web development, scientific and mathematical
computing to desktop graphical user Interfaces.
• The syntax of the language is clean, and length of the code is
relatively short.
• It allows to think about the problem rather than focusing on the
syntax
10/10/2023 Prof. SHIV VEER SINGH 2
Difference between Python and C Language
Python Language C Language
1. Python is an interpreted, high-level, 1. C is a general-purpose compiled,
general-purpose programming language. procedural computer programming
language.
2. Interpreted programs execute slower 2. Compiled programs execute faster as
as compared to compiled programs. compared to interpreted programs.
3. It is easier to write a code in Python as 3. Program syntax is harder than Python.
the number of lines is less comparatively.
4. No pointers functionality available 4. Pointers are available in C.
in Python
10/10/2023 Prof. SHIV VEER SINGH 3
A Brief History of Python (CO1)
• Guido Van Rossum was doing its application-based work in
December of 1989 at Centrum Wiskunde & Informatica (CWI)
which is situated in Netherland.
• It was started firstly as a hobby project because he was looking
for an interesting project to keep him occupied during Christmas.
10/10/2023 Prof. SHIV VEER SINGH 4
A Brief History of Python Cont…(CO1)
• The programming language which Python is said to have
succeeded is ABC Programming Language.
• He had already helped to create ABC earlier in his career and he
had seen some issues with ABC but liked most of the features.
• After that what he did as very clever. He had taken the syntax of
ABC, and some of its good features.
10/10/2023 Prof. SHIV VEER SINGH 5
A Brief History of Python Cont…(CO1)
• It came with a lot of complaints too, so he fixed those issues
completely and had created a good scripting language which had
removed all the flaws.
• The inspiration for the name came from BBC’s TV Show – ‘Monty
Python’s Flying Circus’, as he was a big fan of the TV show and also he
wanted a short, unique and slightly mysterious name for his invention
and hence he named it Python!
10/10/2023 Prof. SHIV VEER SINGH 6
A Brief History of Python Cont… (CO1)
• The language was finally released in 1991.
• When it was released, it used a lot fewer codes to express the
concepts, when we compare it with Java, C++ & C.
• Its main objective is to provide code readability and advanced
developer productivity.
10/10/2023 Prof. SHIV VEER SINGH 7
Applications areas of python (CO1)
10/10/2023 Prof. SHIV VEER SINGH 8
Features of Python (CO1)
10/10/2023 Prof. SHIV VEER SINGH 9
Features of Python (CO1)
• A simple language which is easier to learn.
• Free and open-source.
• Portability.
• Extensible and Embeddable
– easily combine pieces of C/C++ or other languages with Python code.
• A high-level, interpreted language.
• Large standard libraries to solve common tasks.
10/10/2023 Prof. SHIV VEER SINGH 10
Features of Python (CO1)
• Object-oriented
– Everything in Python is an object.
– Object oriented programming (OOP) helps to solve a complex problem
intuitively.
– Structure supports such concepts as polymorphism, operation overloading, and
multiple inheritance.
• It supports functional and structured programming methods as well as
OOP.
• It can be used as a scripting language or can be compiled to byte-code
for building large applications.
10/10/2023 Prof. SHIV VEER SINGH 11
Features of Python (CO1)
• It supports automatic garbage collection.
• Scalable
– Python provides a better structure and support for large programs than
shell scripting.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and
Java.
• Databases
– Python provides interfaces to all major commercial databases.
10/10/2023 Prof. SHIV VEER SINGH 12
Getting Python (CO1)
• The most up-to-date and current source code, binaries,
documentation, news, etc., is available on the official website of
Python
[Link]
• Python documentation can be downloaded from
[Link]
10/10/2023 Prof. SHIV VEER SINGH 13
The Programming Cycle for Python (CO1)
• Python's development cycle is dramatically shorter than that of
traditional languages.
• In Python, there are no compile or link steps.
• Python programs simply import modules at runtime and use the
objects they contain.
• Python programs run immediately after changes are made.
• And in cases where dynamic module reloading can be used, it's
even possible to change and reload parts of a running program
without stopping it at all.
10/10/2023 Prof. SHIV VEER SINGH 14
The Programming Cycle for Python (CO1)
Traditional Development Cycle Python’s Development Cycle
Start the application
Start the application
Test behavior
Test behavior Stop the application
Stop the application Edit the program code
Edit the program code Python’s Development Cycle with Module Reloading
Start the application
Recompile code
Test behavior
Relink the executable Edit the program code
10/10/2023 Prof. SHIV VEER SINGH 15
Elements of Python (CO1)
• Keywords and Identifiers
• Variables
• Data types and type conversion
• Operators in Python
• Expressions in Python
10/10/2023 Prof. SHIV VEER SINGH 16
Keywords (CO1)
• Keywords are the reserved words in Python.
• We cannot use a keyword as a variable name, function name
or any other identifier. They are used to define the syntax and
structure of the Python language.
• In Python, keywords are case sensitive.
• All the keywords except True, False and None are in
lowercase, and they must be written as they are.
• Example
– and, as, assert, await, break, class, continue, def, del, elif, else,
except, finally, for, global, if, import, in, is, lambda, not, or, pass,
raise, return, try, while, with, yield
10/10/2023 Prof. SHIV VEER SINGH 17
Identifiers (CO1)
An identifier is a name given to entities like class, functions,
variables, etc. It helps to differentiate one entity from
another.
10/10/2023 Prof. SHIV VEER SINGH 18
Rules for writing Identifiers (CO1)
• Identifiers can be a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore _.
• An identifier cannot start with a digit.
• Keywords cannot be used as identifiers.
• Cannot use special symbols like !, @, #, $, % etc. in identifier.
• An identifier can be of any length.
10/10/2023 Prof. SHIV VEER SINGH 19
Variables (CO1)
• A variable is a location in memory used to store some data (value).
• Unique names are given to them to differentiate between different
memory locations.
• No need to declare a variable before using it. The declaration
happens automatically when a value is assigned to a variable.
• The Assignment operator (=) is used to assign values to variables.
10/10/2023 Prof. SHIV VEER SINGH 20
Variables (CO1)
• The operand to the left of the = operator is the name of the
variable and the operand to the right of the = operator is the
value stored in the variable.
• For example
>>> num = 347 # An integer assignment
>>> x = 45.89 # A floating point
>>> name = “Aman" # A string
10/10/2023 Prof. SHIV VEER SINGH 21
Multiple Assignment in Variables (CO1)
• A single value may be assigned to several variables simultaneously.
• For example
>>> a = b = c = 1
• Here, an integer object is created with the value 1, and all three
variables are assigned to the same memory location.
• It also allows to assign multiple objects to multiple variables.
• For example −
>>> a, b, c = 23, 29.45, “Ram”
• Here, two integer objects with values 23 and 29.45 are assigned to
variables a and b respectively, and one string object with the value
“Ram" is assigned to the variable c.
10/10/2023 Prof. SHIV VEER SINGH 22
Data types (CO1)
• Every value in Python has a datatype, that are used to
define the operations possible on them and the storage
method for each of them.
• Since everything is an object in Python programming, data
types are classes and variables are instance (object) of
these classes
10/10/2023 Prof. SHIV VEER SINGH 23
Standard Data types (CO1)
Data Types Keyword
Text Type str
Numeric Types int, float, complex
Sequence Types list, tuple, range
Mapping Type dict
Set Types set
Boolean Types bool
Binary Types bytes
10/10/2023 Prof. SHIV VEER SINGH 24
Numbers (CO1)
• They store numeric values. Number objects are created when a value is
assigned to them. For ex:
>>> var1 = 1
>>> var2 = 10
• They can be deleted the reference to a number object by using the del
statement. The syntax of the del statement is
del var1[,var2[,var3[....,varN]]]]
• A single object or multiple objects can be deleted by using the del statement.
For example
>>> del var
>>> del var_a, var_b
10/10/2023 Prof. SHIV VEER SINGH 25
Types of Number Types (CO1)
1. int (signed integers)
2. float (floating point real values)
3. complex (complex numbers)
10/10/2023 Prof. SHIV VEER SINGH 26
Examples of Number Types (CO1)
int float complex
10 0.0 3.14j
100 15.20 45.j
-786 -21.9 9.322e-36j
0o80 32.3+e18 .876j
-0o490 -90 -.6545+0J
-0x260 -32.54E100 3e+26J
10/10/2023 Prof. SHIV VEER SINGH 27
Strings (CO1)
• Strings in Python are identified as a contiguous set of characters
represented in the quotation marks.
• Python allows for either pairs of single or double quotes.
• Subsets of strings can be taken using the slice operator ([ ] and [:] )
with indexes starting at 0 in the beginning of the string and working
their way from -1 at the end.
• The plus (+) sign is the string concatenation operator and the
asterisk (*) is the repetition operator.
10/10/2023 Prof. SHIV VEER SINGH 28
Strings (CO1)
• For example
>>> str = ‘Hello World!’
>>> print(str) # Prints complete string
>>> print(str[0]) # Prints first character of the string
>>> print(str[2:5]) # Prints characters starting from 3rd to 5th
>>> print(str[2:]) # Prints string starting from 3rd character
>>> print(str * 2) # Prints string two times
>>> print(str + ‘TEST’) # Prints concatenated string
10/10/2023 Prof. SHIV VEER SINGH 29
Slicing Strings (CO1)
Slicing
• A range of characters can be returned by using the slice syntax.
• Specify the start index and the end index, separated by a colon, to
return a part of the string.
Example
Get the characters from position 2 to position 5 (not included):
Program
b = "Hello, World!"
print(b[2:5])
Program Output
llo
10/10/2023 Prof. SHIV VEER SINGH 30
Program to demonstrate slicing of Strings (CO1)
# String slicing Output:
String ='ASTRING' String slicing
# Using slice constructor AST
s1 = slice(3) SR
s2 = slice(1, 5, 2) GITA
s3 = slice(-1, -12, -2)
print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
10/10/2023 Prof. SHIV VEER SINGH 31
Output of slicing of Strings (CO1)
Output:
String slicing
AST
SR
GITA
10/10/2023 Prof. SHIV VEER SINGH 32
Lists (CO1)
• A List is an ordered sequence of item, It contains items separated by
commas and enclosed within square brackets ([]).
• To some extent, lists are like arrays in C. One difference between
them is that all the items belonging to a list can be of different data
type.
• Declaring a list is straight forward. Items separated by commas are
enclosed within brackets [ ].
10/10/2023 Prof. SHIV VEER SINGH 33
Lists (CO1)
• >>> a = [1, 2.2, 'python']
– The values stored in a list can be accessed using the slice operator ([ ] and [:])
with indexes starting at 0 in the beginning of the list.
• The plus (+) sign is the list concatenation operator, and the asterisk
(*) is the repetition operator.
10/10/2023 Prof. SHIV VEER SINGH 34
Lists (CO1)
>>> list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
>>> tinylist = [123, 'john’]
>>> print(list) # Prints complete list
>>> print(list[0]) # Prints first element of the list
>>> print(list[1:3]) # Prints elements starting from 2nd till 3rd
>>> print(list[2:]) # Prints elements starting from 3rd element
>>> print(list * 2) # Prints list two times
>>> print(list + tinylist) # Prints concatenated lists
10/10/2023 Prof. SHIV VEER SINGH 35
Tuple (CO1)
• A tuple is similar to the list. A tuple consists of several values separated
by commas. Unlike lists, however, tuples are enclosed within
parentheses.
• The main differences between lists and tuples are: Lists are enclosed in
brackets ( [ ] ) and their elements and size can be changed, while tuples
are enclosed in parentheses ( ( ) ) and cannot be updated.
• Tuples can be thought of as read-only lists.
• The only difference is that tuples are immutable. Tuples once created
cannot be modified.
• Tuples are used to write-protect data and are usually faster than list as it
cannot change dynamically.
10/10/2023 Prof. SHIV VEER SINGH 36
Tuple (CO1)
>>> tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
>>> tinytuple = (123, 'john’)
>>> print(tuple) # Prints complete tuple
>>> print(tuple[0]) # Prints first element of the tuple
>>> print(tuple[1:3]) # Prints elements starting from 2nd till 3rd
>>> print(tuple[2:]) # Prints elements starting from 3rd element
>>> print(tuple * 2) # Prints tuple two times
>>> print(tuple + tinytuple) # Prints concatenated tuples
10/10/2023 Prof. SHIV VEER SINGH 37
Set (CO1)
• Set is an unordered collection of unique items.
• Set is defined by values separated by comma inside braces { }.
• Items in a set are not ordered.
• Set operations can be performed like union, intersection on two sets. Set
have unique values. They eliminate duplicates.
• indexing has no meaning as set are unordered collection. Hence the
slicing operator [] does not work.
• For example
>>>a = {1,2,2,3,3,3}
>>> a
{1, 2, 3}
10/10/2023 Prof. SHIV VEER SINGH 38
Set (CO1)
Method
Add() To add one item to a set use the add() method.
Update() To add items from another set into the current set,
use the update() method.
Remove() To remove an item in a set, use the remove(), or
the discard() method.
10/10/2023 Prof. SHIV VEER SINGH 39
Dictionary (CO1)
• Dictionary is an unordered collection of key-value pairs.
• It is generally used when we have a huge amount of data.
• Dictionaries are optimized for retrieving data. It is must to know the key to
retrieve the value.
• A dictionary key can be almost any Python type but are usually numbers or
strings. Values, on the other hand, can be any arbitrary Python object.
• Dictionaries are defined within braces {} with each item being a pair in the
form key: value. Key and value can be of any type.
• For example
>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>
10/10/2023 Prof. SHIV VEER SINGH 40
Dictionary (CO1)
# empty dictionary:
my_dict = { }
# dictionary with integer keys
my_dict = {1: ‘apple’ , 2 : ‘ball’}
# dictionary with mixed keys
my_dict = {‘name’: ‘apple’ , 1 : [2,4,6]}
# from sequence having each item as a pair
My_dict = dict([(1 , ’apple’) , (2, ‘banana’)])
10/10/2023 Prof. SHIV VEER SINGH 41
Dictionary (CO1)
this_dict = { "brand": "Ford", "model": "Mustang", "year": 1964}
x = this_dict["model"]
print(x)
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
x = [Link]("model")
print(x)
10/10/2023 Prof. SHIV VEER SINGH 42
car = { "brand": "Ford", "model": "Mustang", "year": 1964 }
x = [Link]()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
10/10/2023 Prof. SHIV VEER SINGH 43
Dictionary (CO1)
Method Description
Clear() Remove all items from the dictionary
Copy() Return a shallow copy of the dictionary
Get(key,[d]) Return the value of ke. If key doesnot exit, return d
Items() Return a new view of the dictionary’s
items(key,value)
Keys() Return a new view of the dictionary’s keys
Values() Return a new view of the dictionary’s values
Update([others]) Update the dictionary with the key/value pairs
from other, overwriting existing keys.
10/10/2023 Prof. SHIV VEER SINGH 44
Type conversion (CO1)
• The process of converting the value of one data type
(integer, string, float, etc.) to another data type is called
type conversion.
• Python has two types of type conversion.
– Implicit Type Conversion
– Explicit Type Conversion
10/10/2023 Prof. SHIV VEER SINGH 45
Implicit Type conversion (CO1)
• Python automatically converts one data type to another data
type without any user involvement.
• It always converts smaller data types to larger data types to
avoid the loss of data.
• Example
>>> a = 4
>>> b = 2.3
>>> c = a + b
• In above example, data type of a and b are int and float,
respectively. Data type of c will be float and its value is 6.3
10/10/2023 Prof. SHIV VEER SINGH 46
Explicit Type conversion (CO1)
• In Explicit Type Conversion, users convert the data type of an
object to required data type.
• The predefined functions like int(), float(), str() are used to
perform explicit type conversion.
• This type of conversion is also called typecasting because the
user casts/changes the data type of the objects.
• Syntax
<datatype>(expression)
• Example
>>> a = 2.6
>>> c = int(a)
10/10/2023 Prof. SHIV VEER SINGH 47
Function of type conversion (CO1)
Function Description
int(x) Convert x to an integer
float(x) Convert x to a float number
str(x) Convert x to a string
tuple(x) Convert x to a tuple
list(x) Convert x to a list
set(x) Convert x to a set
ord(x) Convert x to ASCII code
bin(x) Convert x to a binary
oct(x) Convert x to an octal
hex(x) Convert x to a hexadecimal
chr(x) Convert x to a character
10/10/2023 Prof. SHIV VEER SINGH 48
Operators in Python (CO1)
Python language supports the following types of operators.
• Arithmetic Operators
• Relational Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
10/10/2023 Prof. SHIV VEER SINGH 49
Arithmetic Operators (CO1)
Example
Operator Description
(a=5, b=3)
+ Adds values on either side of the operator. a+b=8
- Subtracts right hand operand from left hand operand. a–b=2
* Multiplies values on either side of the operator a * b = 15
a/b=
/ Divides left hand operand by right hand operand
1.6667
% Divides left hand operand by right hand operand and a%b=2
a**b =53=
** Performs exponential (power) calculation on operators
125
The division of operands where the result is the quotient in
// a//b=1
which the digits after the decimal point are removed.
10/10/2023 Prof. SHIV VEER SINGH 50
Relational Operators (CO1)
Example
Operator Description
a=5, b=3
If the values of two operands are equal, then the condition a == b is not
==
becomes true true.
If values of two operands are not equal, then condition a!=b is true
!=
becomes true.
If the value of left operand is greater than the value of right a > b is true
>
operand, then condition becomes true.
If the value of left operand is less than the value of right a < b is not
<
operand, then condition becomes true. true
If the value of left operand is greater than or equal to the a >= b is
>=
value of right operand, then condition becomes true. true
If the value of left operand is less than or equal to the value a <= b is not
<=
of right operand, then condition becomes true. true
10/10/2023 Prof. SHIV VEER SINGH 51
Assignment Operators (CO1)
Operator Description
a=b
=
Assigns values from right side operands(b) to left side operand (a)
a+=b is same as a = a + b
+=
It adds right operand to the left operand and assign the result to left operand
a-=b is same as a = a - b
-=
It subtracts right operand from the left operand and assign the result to left operand
a*=b is same as a = a * b
*=
It multiplies right operand with the left operand and assign the result to left operand
a/=b is same as a = a / b
/=
It divides left operand with the right operand and assign the result to left operand
10/10/2023 Prof. SHIV VEER SINGH 52
Assignment Operators (CO1)
Operator Description
a%=b is same as a = a % b
%=
It takes modulus using two operands and assign the result to left operand
a**=b is same as a = a ** b
**= Performs exponential (power) calculation on operators and assign value to the
left operand
a//=b is same as a = a //b
//=
It performs floor division on operators and assign value to the left operand
10/10/2023 Prof. SHIV VEER SINGH 53
Logical Operators (CO1)
Logical operators are the and, or, not operators.
Operator Description
and True if both the operands are true
or True if either of the operands is true
not True if operand is false (complements the operand)
10/10/2023 Prof. SHIV VEER SINGH 54
Logical Operators (CO1)
a b a and b a or b not a
True True True True False
True False False True False
False True False True True
False False False False True
10/10/2023 Prof. SHIV VEER SINGH 55
Bitwise Operators (CO1)
• Bitwise operators manipulate the data at bit level.
• These are applicable on integer values.
• Types
& (Bitwise and operator)
| (Bitwise or operator)
^ (Bitwise XOR operator)
~ (Bitwise one’s complement operator)
<< (Bitwise left-shift operator)
>> (Bitwise right-shift operator)
10/10/2023 Prof. SHIV VEER SINGH 56
Bitwise Operators (CO1)
a b a&b a|b a^b ~a
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0
10/10/2023 Prof. SHIV VEER SINGH 57
Bitwise Operators (CO1)
Operator Let a = (92)10 =(0101 1100)2 and b = (14)10 = (0000 1110)2
0101 1100
& 0000 1110
& c = (a & b) = 92 & 14
0000 1100 = (12)10
0101 1100
| 0000 1110
I c = (a | b) = 92 | 14
0101 1110 = (94)10
0101 1100
^ 0000 1110
^ c = (a ^ b) = 92 | 14
0101 0010 = (82)10
10/10/2023 Prof. SHIV VEER SINGH 58
Bitwise Operators (CO1)
Let a = (92)10 =(0101 1100)2 and b = (14)10 = (0000 1110)2
Operator
~ c = ~a = ~92 c = ~(0101 1100) = 1010 0011
<< c = a<< 1 = 46<< 1 C = 00101 110 << 1 = 01011100 = (92)10
>> c = a >> 2 = 92>> 2 C = 0101 1100 >> 2 = 0001 0111 = (23)10
10/10/2023 Prof. SHIV VEER SINGH 59
Membership Operators (CO1)
• in and not in are the membership operators in Python.
• They are used to test whether a value or variable is found
in a sequence (string, list, tuple, set and dictionary).
• In a dictionary, we can only test for presence of key, not
the value.
Example
Operator Description Result
x = {2,3,5}
in True if value/variable is found in the sequence 5 in x True
True if value/variable is not found in the
not in 5 not in x False
sequence
10/10/2023 Prof. SHIV VEER SINGH 60
Identity Operators (CO1)
• Identity operators compare the memory locations of two objects.
• is and is not are the identity operators in Python.
• They are used to check if two values (or variables) are located on the
same part of the memory.
• Two variables that are equal does not imply that they are identical.
Example
Operator Description a = ‘Hello’ Result
b = ‘Hello’
True if the operands are identical (refer to the
is a is b True
same object)
True if the operands are not identical (do not
is not a is not b False
refer to the same object)
10/10/2023 Prof. SHIV VEER SINGH 61
Operator Precedence and associativity(CO1)
• When an expression contains two or more than two
operators, then it is evaluated based on operator
precedence and associativity.
• Each operator of same precedence is grouped in same
level and operator of higher precedence is evaluated first.
• Two or more operators having equal precedence are
evaluated either left-to-right(LTR) or right-to-left(RTL)
based on their associativity.
10/10/2023 Prof. SHIV VEER SINGH 62
Operator Precedence and associativity(CO1)
Operator Description
() Parenthesis
** Exponentiation
~,+,- Unary operators
*,/,//,% Arithmetic multiply, division, floor and modulo division
+, - Addition and subtraction
>>,<< Bitwise left and right shift operator
& Bitwise and operator
^ Bitwise Ex-or operator
| Bitwise or operator
10/10/2023 Prof. SHIV VEER SINGH 63
Operator Precedence and associativity(CO1)
Operator Description
<=,>=,<,> Relational inequality operators
==, != Equal and not equal operators
=,*=,/=,//=,%=,+=,-=,**=,&= Assignment operators
is, is not Identity operators
in, not in Membership operators
not Logical not operator
and Logical and operator
or Logical or operator
10/10/2023 Prof. SHIV VEER SINGH 64
Expressions in Python (CO1)
• Expressions are representations of value.
• They are different from statement in the fact that
statements do something while expressions are
representation of value.
• Python expression contains identifiers, literals, and
operators.
• For Example
x = a*b + c/d –f is an expression.
10/10/2023 Prof. SHIV VEER SINGH 65
Why use conditional statements? (CO2)
• A conditional statement is used to determine whether a
certain condition exists before code is executed.
• Conditional statements can help improve the efficiency of
your code by providing you with the ability to control the flow
of your code, such as when or how code is executed.
• This can be very useful for checking whether a certain
condition exists before the code begins to execute, as you
may want to only execute certain code lines when certain
conditions are met.
10/10/2023 Prof. SHIV VEER SINGH 66
Conditional Statements (Decision Making) (CO2)
• Decision making is anticipation of conditions occurring while
execution of the program and specifying actions taken
according to the conditions.
• Conditional Statements are features of a programming
language, which perform different computations or actions
depending on whether the given condition evaluates to true
or false.
10/10/2023 Prof. SHIV VEER SINGH 67
Types of Conditional Statements (CO2)
• There are following four types of conditional statements in
Python-
if statement
if else statement
if elif statement
Nested if else
10/10/2023 Prof. SHIV VEER SINGH 68
if Statement (CO2)
• if Statement is used to run a statement conditionally i.e. if
given condition is true then only the statement given in if
block will be executed.
• An if statement consists of a Boolean expression followed by
one or more statements.
• Syntax: if Boolean Expression:
Statements
• Example: age = int(input("Enter your age in years: "))
if age >= 18:
print("You can VOTE")
print("Congrats!“)
10/10/2023 Prof. SHIV VEER SINGH 69
if Statement flowchart (CO2)
Boolean
False
expression
(Condition)
True
Statements
Statement-x
10/10/2023 Prof. SHIV VEER SINGH 70
Important points about if Statement (CO2)
• The colon (:) is significant and required. It separates
the header of the compound statement from the body.
• The line after the colon must be indented. It is standard in
Python to use four spaces for indenting.
• All lines indented the same amount after the colon will be
executed whenever the Boolean expression is true.
10/10/2023 Prof. SHIV VEER SINGH 71
if else Statement (CO2)
• An if statement can be followed by an optional else
statement, which executes when the Boolean expression is
FALSE.
• Syntax: if Boolean Expression:
Statement-A
else:
Statement-B
• Example: percentage = int(input("Enter your percentage: "))
if percentage > 33:
print("PASS")
else:
print("FAIL")
10/10/2023 Prof. SHIV VEER SINGH 72
if else Statement flow chart (CO2)
Boolean
expression
True False
(Condition)
Statement-A Statement-B
Statement-x
10/10/2023 Prof. SHIV VEER SINGH 73
if elif Statement (CO2)
• The if elif statement allows you to check multiple expressions
for TRUE and execute a block of code as soon as one of the
conditions evaluates to TRUE.
• Unlike else, for which there can be at most one statement,
there can be an arbitrary number of elif statements following
an if.
if Boolean Expression1:
• Syntax:
Statement-A
elif Boolean Expression2:
Statement-B
elif Boolean Expression3:
Statement-C
else:
Statement-D
10/10/2023 Prof. SHIV VEER SINGH 74
if elif Statement flow chart (CO2)
Boolean True
Expression-1 statement-A
False
Boolean True
statement-B
Expression-2
False
Boolean True
statement-C
Expression-3
False
statement-D
statement-X
10/10/2023 Prof. SHIV VEER SINGH 75
if elif Statement Example (CO2)
percentage = int(input("Enter your percentage: "))
if percentage >= 90:
print("Grade A")
elif percentage >= 80:
print("Grade B")
elif percentage >= 70:
print("Grade C")
elif percentage >= 60:
print("Grade D")
elif percentage >= 50:
print("Grade E")
else:
print("Fail")
10/10/2023 Prof. SHIV VEER SINGH 76
Nested if else Statement (CO2)
• One conditional can also be nested within another.
• You can use one if or else if statement inside
another if or else.
• Syntax:
if Boolean Expression1:
Statement-A
else:
if Boolean Expression-2:
Statement-B
else:
Statement-C
10/10/2023 Prof. SHIV VEER SINGH 77
Nested if else Statement (CO2)
Boolean True
Statement-A
expression-1
False
Boolean True
Statement-B
expression-2
False
Statement-C
Statement-X
10/10/2023 Prof. SHIV VEER SINGH 78
Nested if else Statement Example (CO2)
a = int(input("Enter first Number"))
b = int(input("Enter Second Number"))
c = int(input("Enter third Number"))
if a > b:
if a > c:
print(a, "is greatest")
else:
print(b, "is greatest")
else:
if b > c:
print(b, "is greatest")
else:
print(c, "is greatest")
10/10/2023 Prof. SHIV VEER SINGH 79
Why use loop statements? (CO2)
• Program statements are executed sequentially one after
another.
• In some situations, a block of code needs to be executed
multiple times.
• To achieve this, we use looping statements in Python
programming.
10/10/2023 Prof. SHIV VEER SINGH 80
Python Loops (CO2)
• Loops allow the execution of statement of a group of
statement multiple times.
• In order to enter the loop there are certain conditions.
• Once the condition becomes false, the loop stops and the
control moves out of loop.
10/10/2023 Prof. SHIV VEER SINGH 81
Types of Python Loops (CO2)
while loop statement
for in loop statement
Nested loop statement
10/10/2023 Prof. SHIV VEER SINGH 82
while Loop (CO2)
• A while loop statement in Python programming language
repeatedly execute a target statement as long as a given
condition is true.
• Syntax:
while Expression:
Statements
10/10/2023 Prof. SHIV VEER SINGH 83
while flowchart (CO2)
Entry
Test False
expression
True
Statements
(while loop body)
Exit loop
10/10/2023 Prof. SHIV VEER SINGH 84
Program to find the sum of first n natural numbers (CO2)
num = int(input("Enter a number: "))
sum_n = 0
while num > 0:
sum_n = sum_n + num
num = num - 1
print("The Sum is: ", sum_n)
Output:
Enter a number: 4
The sum is: 10
10/10/2023 Prof. SHIV VEER SINGH 85
for in Loop (CO2)
• A for loop is used for iterating over a sequence (that is either
a list, a tuple, a dictionary, a set, or a string).
• for loop is a Python loop which repeats a group of statements
a specified number of times.
• The for loop provides the syntax where the following
information is provided.
– Boolean condition
– The initial value of counting variable.
– Updation of counting variable.
• Syntax:
for value in sequence:
Statements
10/10/2023 Prof. SHIV VEER SINGH 86
Important points about “for in” loop syntax (CO2)
• Here, value is the variable that takes the value of the item
inside the sequence on each iteration.
• Loop continues until we reach the last item in the sequence.
• The body of for loop is separated from the rest of the code
using indentation.
10/10/2023 Prof. SHIV VEER SINGH 87
“for in” loop flowchart (CO2)
for each item
in sequence
Last item Yes
reached?
No
Statements
(while loop body)
Exit loop
10/10/2023 Prof. SHIV VEER SINGH 88
Program to find the sum of all numbers stored in a list (CO2)
numbers = [10, 20, 5, 15, 25, 35, 30]
sum_num = 0
for val in numbers:
sum_num = sum_num + val
print("The sum of numbers is:", sum_num)
Output:
The sum of numbers is: 140
10/10/2023 Prof. SHIV VEER SINGH 89
range() function (CO2)
• We can generate a sequence of numbers using range()
function.
• range(10) will generate numbers from 0 to 9 (10 numbers).
• range() function returns the list, all the operations that can be
applied on the list can be used on it.
• We can also define the start, stop and step size as
– range(start, stop, step_size).
– step_size defaults to 1 if not provided.
10/10/2023 Prof. SHIV VEER SINGH 90
Example of range() function (CO2)
for i in range(0, 100, 25):
print(i)
Output:
0
25
50
75
10/10/2023 Prof. SHIV VEER SINGH 91
Nested Loops (CO2)
• Python programming language allows to use one loop inside
another loop.
• Syntax:
for value1 in sequence:
for value2 in sequence:
statements(s)
statements(s)
10/10/2023 Prof. SHIV VEER SINGH 92
Nested loop Example (CO2)
for i in range(1, 5):
for j in range(i):
print(i, end=" ")
print()
Output:
1
22
333
4444
10/10/2023 Prof. SHIV VEER SINGH 93
Program to print all prime numbers from a list (CO2)
n = [2, 4, 5, 6, 8, 11, 14, 25, 27, 31]
for x in n:
i = 1;
flag = 0
while i <= x:
if x % i == 0:
flag = flag + 1
i = i + 1;
if flag == 2:
print(x)
Output: 2 5 11 31
10/10/2023 Prof. SHIV VEER SINGH 94
break statement (CO2)
• The break statement is used to exit a for or a while loop.
• The purpose of this statement is to end the execution of the
loop (for or while) immediately and the program control goes
to the statement after the last statement of the loop.
• If there is an optional else statement in while or for loop it
skips the optional clause also.
• Syntax:
for variable in sequence:
statement_1
statement_2
if expression3 :
break
10/10/2023 Prof. SHIV VEER SINGH 95
Example of break Statement (CO2)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
num_sum = 0
count = 0
for x in numbers:
num_sum = num_sum + x
count = count + 1
if count == 5:
break
print("Sum of first ", count, "integers is: ", num_sum)
Output:
Sum of first 5 integers is: 15
10/10/2023 Prof. SHIV VEER SINGH 96
continue statement (CO2)
• The continue statement is used in a while or for loop to take
the control to the top of the loop without executing the rest
statements inside the loop.
• Syntax:
for variable in sequence:
statement_1
statement_2
if expression3 :
continue
10/10/2023 Prof. SHIV VEER SINGH 97
Example of continue Statement (CO2)
for x in range(7):
if x == 3 or x == 6:
continue
print(x)
Output:
0
1
2
4
5
10/10/2023 Prof. SHIV VEER SINGH 98
Python pass statement (CO2)
• In Python programming, the pass statement is a null
statement.
• The difference between a comment and a pass statement in
Python is that while the interpreter ignores a comment
entirely, pass is not ignored.
• However, nothing happens when the pass is executed. It
results in no operation.
• Syntax: if Boolean expression :
pass
else:
Statements
10/10/2023 Prof. SHIV VEER SINGH 99
Example of continue Statement (CO2)
number = int(input("Enter a number: "))
if number is 2:
pass
else:
print("Number is: ", number)
Output:
Number is: 5
10/10/2023 Prof. SHIV VEER SINGH 100
Expression Evaluation (CO2)
• An expression is a combination of values, variables, and
operators.
• If you type an expression on the command line, the
interpreter evaluates it and displays the result
• The evaluation of an expression produces a value, which is
why expressions can appear on the right hand side of
assignment statements.
• Evaluating an expression is not quite the same thing as
printing a value.
• When the Python shell displays the value of an expression, it
uses the same format you would use to enter a value.
10/10/2023 Prof. SHIV VEER SINGH 101
Example of Expression Evaluation (CO2)
a = 20
b = 10
c =a+b–5
print(c)
Output:
25
10/10/2023 Prof. SHIV VEER SINGH 102
Float Representation in Python (CO2)
• The float type in Python represents the floating point number.
• Float is used to represent real numbers and is written with a
decimal point dividing the integer and fractional parts.
• For example, 97.98, 32.3+e18, -32.54e100 all are floating
point numbers.
10/10/2023 Prof. SHIV VEER SINGH 103
Float Representation in Python (CO2)
• Python float values are represented as 64-bit double-precision
values.
• The maximum value any floating-point number can be is
approx 1.8 x 10308.
• Any number greater than this will be indicated by the
string inf in Python.
print(1.7e308)
# greater than 1.8 * 10^308 will
print 'inf'
print(1.82e308)
10/10/2023 Prof. SHIV VEER SINGH 104
Float Representation in Python (CO2)
• float.as_integer_ratio(): Returns a pair of integers whose
ratio is exactly equal to the actual float having a positive
denominator.
• In case of infinites, it raises overflow error and value errors on
Not a number (NaNs).
b = 3.5
d = b.as_integer_ratio()
Output:
print(d[0], "/", d[1])
7/2
10/10/2023 Prof. SHIV VEER SINGH 105
Float Representation in Python (CO2)
• float.is_integer() : Returns True in case the float instance is
finite with integral value, else, False.
print((-5.0).is_integer())
print((4.8).is_integer())
print(float.is_integer(275.0))
Output:
True
False
True
10/10/2023 Prof. SHIV VEER SINGH 106
Float Representation in Python (CO2)
• [Link](): Returns a representation of a floating-point
number as a hexadecimal string.
a = [Link](35.0)
print(a)
Output:
0x1.1800000000000p+5
10/10/2023 Prof. SHIV VEER SINGH 107
10/10/2023 Prof. SHIV VEER SINGH 108