Download as pdf or txt
Download as pdf or txt
You are on page 1of 154

UNIT-1

(part-2 topics)
Prepared By
B.JAYARAM
Mtech(PhD)
CSD dept
Introduction to Python
• Python is a general purpose, dynamic, high-level,
interpreted, Object Oriented programming
language
•.
• It was created by Guido van Rossum ,started
implementation in 1989 and released in 1991 at CWI
in Netherland.
• Easiest than c,c++,java.
• Python supports multiple programming , pattern
including object-oriented imperative and functional or
procedure programming styles .
• What is the difference between compile and
• Interpreter
• Complier the program source code execute at a time -----

• Interpreter the program source code is execute line by line (or one
line after another )
OR
• Python is a general purpose programming
language that is often applied in scripting roles.

• So Python is programming language as well as


scripting language.

• Python is also called as Interpreted language


Differences between program
and scripting language
Program Scripting

1) a program is executed (i.e. 1) A script is


the source is first compiled,
and the result of that interpreted
compilation is expected)

2) A "program" in general, 2) A "script" is code written in


is asequence of instructions a scripting language. A
scripting language is nothing
written so that a computer
but a type of programming
can perform certain task. language in which we can
write code to control
another software application.
Why Python?
• Python works on different platforms (Windows, Mac,
Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English
language.
• Python has syntax that allows developers to write
programs with fewer lines than some other
programming languages.
• Python runs on an interpreter system, meaning that
code can be executed as soon as it is written. This means
that prototyping can be very quick.
• Python can be treated in a procedural way, an object-
orientated way or a functional way.

• It is possible to write Python in an Integrated


Development Environment, such as Thonny, Pycharm,
Netbeans, or Eclipse which are particularly useful when
managing larger collections of Python files.
 We don't need to use data types to declare variable
because it is dynamically typed .
 so we can write a=10 to assign an integer value in an
integer variable.
 Python makes the development and
debugging fast because there is no compilation step
included in Python development, and edit-test-debug
cycle is very fast.
 Python is used for:
1. web development (server-side),
2. software development
3. mathematics,
4. system scripting.
Python Features
1.Easy to Learn and Use
Python is easy to learn as compared to other
programming languages.
Its syntax is straightforward and much the same
as the English language.
There is no use of the semicolon or curly-
bracket, the indentation defines the code block.
It is the recommended programming language
for beginners.
2) Expressive Language
Python can perform complex tasks using a few lines of code.

A simple example, the hello world program you simply


type print("Hello World").

It will take only one line to execute, while Java or C


takes multiple lines.
3) Interpreted Language
• Python is an interpreted language; it means the Python
program is executed one line at a time. The advantage of
being interpreted language, it makes debugging easy and
portable
4) Cross-platform Language
• Python can run equally on different platforms such as Windows,
Linux, UNIX, and Macintosh, etc.
• So, we can say that Python is a portable language.
• It enables programmers to develop the software for several
competing platforms by writing a program only once.
5) Free and Open Source
• Python is freely available for everyone. It is
freely available on its official
website www.python.org.
• It has a large community across the world that
is dedicatedly working towards make new
python modules and functions. Anyone can
contribute to the Python community. The open-
source means, "Anyone can download its
source code without paying any penny."
6) Object-Oriented Language
• Python supports object-oriented language and concepts
of classes and objects come into existence. It supports
inheritance, polymorphism, and encapsulation, etc.

• The object-oriented procedure helps to programmer to


write reusable code and develop applications in less
code.
7) Extensible
• It implies that other languages such as C/C++ can be used to
compile the code and thus it can be used further in our Python
code.
• It converts the program into byte code, and any platform can
use that byte code.
8) Large Standard Library
• It provides a vast range of libraries for the various fields such
as machine learning, web developer, and also for the
scripting.
• There are various machine learning libraries, such as Tensor
flow, Pandas, Numpy, Keras, and Pytorch, etc.
9) GUI Programming Support
• Graphical User Interface is used for the
developing Desktop application. PyQT5,
Tkinter, Kivy are the libraries which are used
for developing the web application.
10) Integrated
• It can be easily integrated with languages like
C, C++, and JAVA, etc.
• Python runs code line by line like C,C++ Java.
It makes easy to debug the code.
11. Dynamic Memory Allocation
• In Python, we don't need to specify the data-type
of the variable. When we assign some value to
the variable, it automatically allocates the
memory to the variable at run time.
• Suppose we are assigned integer value 15
to x, then we don't need to write int x = 15. Just
write x = 15.
Python History
Python laid its foundation in the late 1980s.
The implementation of Python was started in
December 1989 by Guido Van Rossum at
CWI in Netherland.
In February 1991, Guido Van
Rossum published the code (labeled version
0.9.0)
In 1994, Python 1.0 was released with new
features like lambda, map, filter, and reduce.
Python 2.0 added new features such as list
comprehensions, garbage collection systems.
 On December 3, 2008, Python 3.0 (also called
"Py3K") was released. It was designed to rectify the
fundamental flaw of the language.

 The following programming languages influence


Python:
◦ ABC language.
◦ Modula-3
Python Version List
Python Version Released Date

Python 1.0 January 1994


Python 1.5 December 31, 1997
Python 1.6 September 5, 2000
Python 2.0 October 16, 2000
Python 2.1 April 17, 2001
Python 2.2 December 21, 2001
Python 2.3 July 29, 2003
Python 2.4 November 30, 2004
Python 2.5 September 19, 2006
Python 2.6 October 1, 2008
Python 2.7 July 3, 2010
Python 3.0 December 3, 2008
Python Version Released Date

Python 3.1 June 27, 2009

Python 3.2 February 20, 2011

Python 3.3 September 29, 2012

Python 3.4 March 16, 2014

Python 3.5 September 13, 2015

Python 3.6 December 23, 2016

Python 3.7 June 27, 2018

Python 3.8 October 14, 2019


Python Applications
UNIT-I
• Python Basics Python Objects: Standard Types, Built-in Types, Internal
Types, Standard Type Operators, Standard Type Built-in Functions,
Categorizing the Standard Types, Unsupported Types.

• Python Numbers: Introduction to Numbers, Integers, Floating Point Real


Numbers, Complex Numbers, Operators, Built-in Functions.

• Conditionals and Loops-if, else, elif, for, while, break, continue, pass, List
comprehensions, Generator expressions
TOPIC:1 Python Numbers (or) Numeric
• Numbers data types store numeric values. They are immutable data types,
which means that changing the value of a number data type result in a
newly allocated object.
• Examples :
• Var1 =10
• X=20
TOPIC 2: PYTHON OPERATORS
What is meant by an Operator in Python?

• These are the special symbols in python and are used to execute an
Arithmetic or Logical computation.
• An operator alone cannot perform an activity, it needs an Operand.
• What is an operand?
• An Operand is a value that the operator needs to complete a task.
To understand it clearly, let’s consider an example over here.
>>>10/2 5

Here, in the above example,


we have used a Python Operator called / (Division). 10 and 2 are called
as operands.
The number 5 is called as output of the above execution.
Types of operators in Python:
• Arithmetic operators
• Comparison operators
• Assignment operators
• Logical operators
• Bitwise operators
• Membership operators
• Special operators
• Identity operators
• Membership operators
• 1)Arithmetic operators
• Arithmetic operators are used for executing the mathematical
functions in Python which includes, addition, subtraction,
multiplication, division, etc.
• Let us know the various Arithmetic operators and their purpose in
Python from the below table.
Operator Description Example

+Plus Adds two Operands. 3+3= 6


Right hand Operand subtracted from the
-Minus 20-10=10
left hand operand.

It Multiplies the values on either side of


* Multiplication 10*10 = 100
the operands.

left hand operand divided by right hand


/ Division 50/5 = 10
operand.

It divides the left hand operand by right


% Percent 6/2 = 3
hand one and also returns reminder.

>>> 5.0 / 2
Division that results into whole number 2.5
// Floor division
adjusted to the left in the number line. >>> 5.0 /2
2.0

** Exponent Left operand is raised to the power of right 10 to the power of 30


1) Python (+) Addition operator
Addition operator in python is being used to add two operands (values)
in python programming. Look at the below program to know how it works.
Program
X = 10
Y = 20
x + y = 30
print ( ‘x + y =’, x + y )
When you execute the above program, you will get the below output.
Run
x + y = 30
2) Python (-) Subtraction operator
In python programing, the operator, Subtraction is used to execute a
mathematical function.
which subtracts the right hand operand from the left hand one.
Program:
x = 10 y = 20
# output: x - y = - 10
print (‘x - y =’, x - y )
Run
x - y = - 10
3) Python (*) Multiplication operator
It is used in python programming to multiply the values and thereby to
get output.
Let's consider the below program to understand the multiplication
operator.
Program
x = 10
y = 20
# output: x * y = 200
print (‘x * y =’, x * y )
Run
x * y = 200
4) Python (/) Division operator
Division operator is used to divide the left hand operand by right hand one.
x = 10
y = 20
i.e x/y (10/20 = 0.5 )
Let’s consider it in python way
Program
x = 10
y = 20
# output: x / y = 0.5
print (‘x / y =’, x / y )
Run
x / y = 0.5
5) Python (%) Percentail operator
The Percentile (%) is the string formatting operator in python,
and it is also called as a interpretation operator.
It divides the left hand operand by right hand one and also returns reminder. Ex: x/y
Program
x = 20
y = 10
# output: x % y = 0.
print (‘x % y =’, x % y )
Run
x % y = 0
6)Python (//) Floor division operator
The Floor Operator is used to make a whole number adjusted to the left hand side in the number
line.
Let's check the below program to know how a floor operator works in Python
Program
x = 50
y = 20
# Output: x // y = 2
print('x // y =',x//y)
Run
x // y = 2

Note:( In the above program, actual value that we get is 2.5,


but to match the requirements of the Floor operator, we had to adjust it to the left side, i,e, 2.5 to 2)
7) Python (**) Exponent operator
Exponent operator is used in Python to perform exponential (power) calculations by using operators.
Let's look into this concept with the help of a program.
Program
x = 10
y = 4
# output: x ** y = 10,000
print (‘x ** y =’, x ** y )
Run
x ** y = 10,000
• II) Python Comparison Operators
• The name itself is explaining that this operator is used to compare different things
or values with one another.
• In Python, the Comparison operator is used to analyze either side of the values and
decides the relation between them.
• Comparison operator is also termed as a relational operator because it explains the
connection between them.
• We have different Comparison (Relational) operators.
• Let’s list them down and get to know each operator in detail.
• == Equal
• != Not Equal
• <> Two Operands are not equal
• > Greater Than
• < Less Than
• >= Greater Than or Equal to
• <= Less Than or Equal to
1) Python (==) Equal Comparison Operator
Equal operator is used to compare the two values and to give the result whether they are equal or
not.
If both the values are equal, then it gives the result as True, if not False.
Let's consider below program.
Program
x = 20 y = 25
# Output: x == y is False
print('x == y is',x==y)
Run:
x == y is False
2) Python (!=) Not Equal Comparison Operator
This Not equal operator is used to compare two operands and returns True statement
if they are Not equal, and False if they are Equal.
Program
x = 20
y = 25
# Output: x != y is True
print('x != y is',x!=y)
Run:
x != y is true
3) Python (>) Greater Than Operator
This operator is mainly used in Python to return true if the Left hand value is greater than
right one.
If left hand operand is greater than right hand operand, it returns True as the output.
Ex: 10 is > 8, then the answer becomes True
10 is > 12, then the answer becomes False
Program:
ex :
x = 20
y = 25
# Output: x > y is False
print('x > y is',x>y)
Run:

x > y is False
4) Python (<) Less Than Operator
This Operator compares the right hand operator with the left hand one and if the right hand
one is greater than the left hand one, it returns True statement.
Ex: 10 is < 12, then the answer becomes True
10 is < 8, then the answer becomes False
Program:
x = 20
y = 25
# Output: x < y is True
print('x < y is',x<y)
Run:
x < y is True
5) Python >= Greater Than or Equal to operator
Greater than operator is used in python to evaluate to True
if the left hand operand is >= (greater than or equal) to right hand one
Program:
x = 20
y = 25
# Output: x >= y is False
print('x >= y is',x>=y)
Run:
x >= y. Hence it is False
6) Python <= Less than or equal to operator
Less than or equal to operator returns true if the right hand operator is greater than or equal to left hand one.
Program:
x = 20
y = 25
# Output: x <= y is True
print('x <= y is',x<=y)
Run:
x <=y is True
• III) Python Assignment Operators
• Assignment operator is used to assign value to the event, property, or variable. We
use this operator in python to assign values to variables.
• We have multiple Assignment operators.
• Let’s list them down and know things better.
• = Assign Value
• += Add AND
• -= Subtract AND
• *= Multiply AND
• /= Divide AND
• %= Modulus AND
• **= Exponent AND
• //= Floor Division
• 1) Python (=) Assign value Operator
• This operator assigns values to the left hand operand from the right side
operand.
• Example: 5 = 2+3
• In the above example, the right hand operands are 2 & 3, and have
contributed to construct value 5.
• 2) Python (+=) Add AND Operator
• It adds the value of right operand to the value of left hand operand.
• Let's consider an
• example;
• x = 10,
• x + = 5,
• which will return the value as 15 by adding the right side value to the left
hand one.
• Therefore, the answer is x= 15.
3) Python(-=) Subtract AND Operator
Subtract And operator (-=) subtracts the value of left operand from the right side operand and
returns the output.
Example
x = 10,
y -= 7,
the answer is x = 3
4) Python (*=) Multiply AND Operator
It multiplies the left hand operand with the right hand one and returns the value as output.
Example;
x = 10,
x*=5,
the answer is x = 50.
5) Python (/=) Divide AND Operator
Divide And operator divides the left hand operand with the right hand operand value and gives the result
Example;
x = 10,
x/= 5
the result is x = 2
6) Python (%=) Modulus AND Operator
It divides the value of left hand operand with the right hand one and the reminder that we get through this
task will be placed as a value of x.
Example;
x = 10,
x%= 5
the result is x = 0
7) Python **= Exponent AND operator
It gives us the exponential value of the left hand operand when raised to the power of the value found
in the right hand side.
Example;
x = 10, x**= 5 the result is x = 1,00,000
8) Python (//=) Floor Division
Floor division divides the value found in the left hand side with the value of right hand operand. The
integer value becomes the left hand Operand value.
Example;
x = 7, x//= 4 the result is x = 1
• IV) Python logical Operators
• Logical operators are used in any programming language to make decision
based on multiple conditions.
• In python, we use Logical operators to determine whether a condition is
True or False by taking Operand values as base.
• Let’s consider different logical operators that are used in python
programming.
• And - Logical AND
• Or - Logical OR
• Not - Logical NOT
1) Python and Logical AND operator
AND operator returns the logical value ‘True’ when two Operands are true;
otherwise, it will return False.
Ex: variable A = 10, B = 20,

x = 10
y = 20
# Output: x and y is True
print('x and y is',x and y)
Output:
Ans: A and B is True
2) Python or Logical OR operator
In this Logical OR operator, if any one of the two operands are non zero, then it returns the
True condition. .
Ex: variable A = 10, B = 20,
Program
x = 10
y = 20
# Output: x or y is True
print('x or y is',x or y)
Output:
Ans: a or b is True
3) Python not Logical NOT
Logical NOT is used to reverse the logical state of its operands.
Program
x = 10
y = 20
# Output: not x is False
print('not x is',not x)
Output:
Ans: Not (a and b) is false.
• V) Python Bitwise operators
• Bitwise operators are used in python to perform the operations on
binary numerals or bit patterns. It operates bit by bit.
• & Binary AND
• | Binary OR
• ^ Binary XOR
• ~ Binary Ones Complement
• << Binary Left Shift
• >> Binary Right Shift
1)Python & Binary AND Bitwise Operator
Description: This operator performs bit by bit AND operations on the
values on either side of the operator.
Example Program
a = 10
b = 4
# Print bitwise AND operation
print(a & b)
Output:
0
2) Python | Binary OR Bitwise Operator
Description: This operator performs bit by bit OR operations on
the values on either side of the operator.
Example Program
a = 10
b = 4
# Print bitwise OR operation
print(a | b)
Output: 14
3) Python ^ Binary XOR Bitwise Operator
Description: This operator performs bit by bit exclusive OR
operations on the values on either side of the operator.
Example Program
a = 10
b=4
# print bitwise XOR operation
print(a ^ b)
Output: 14
4) Python ~ Binary Ones Complement Bitwise Operator

Description: The one’s complement of a number’s binary is returned.

Example Program:
a = 10
b=4
# Print bitwise NOT operation
print(~a)

Output: -11
5) Python << Binary Left shift Bitwise Operator

Description: The value to the left operator is shifted to the left as many
times as the value on the right side of the operator.
Example Program
a = 10
b=4
# print bitwise left shift operation
print(a << 2)

Output: 40
6) Python >> Binary Right shift Bitwise Operator

Description: The value to the left of the operator is shifted to the


right as many times as the value on the right of the operator.
a = 10
b=4
# print bitwise right shift operation
print(a >> 2)
Output: 2
• VI) Python Membership operators
• Membership Operators are mainly used in python to find
whether a value or variable is present in a sequence (string,
tuple, list, set, and directory).
• “In” and “Not In” are the two membership operators
available in python.
• 1) Python In Membership Operator
• This In operator is used in python to evaluate if a particular
value is there or not in a sequence.
• The In operator returns True if it the specified element found
in the list, otherwise it returns false.
Example:
x = ["apple", "banana"]
print("banana" in x)
Output: True
• 2) python Not in Membership Operator
• “Not in” operator, the name itself is expressing the meaning
that something is not inside.
• It goes through a particular sequence to find weather a value
is in the specified list or not. If it finds there is no such value,
it returns True, otherwise False.
• Example:
• x = ["apple", "banana"]
• print("pineapple" not in x)
• Output: True
• Python Identity operators
• We have two identity operators in python namely is and is
not. These are also called as special operators and are used to
find if two identical values (or variables) located on the same
part of the memory or not.
• If two variables are equal, that does not mean they are
identical. We have two different operators.
• 1) Python is Identity operator
• This operator returns true statement if two identical operands reside in
the same memory, otherwise false.
Example 1:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
print(x is y)
print(x == y)

Output:
True
False
True
• 2) Python Is not Identity operator
• It will return false if either side of the operator pointing towards the
same thing, otherwise it returns true.
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is not z)
print(x is not y)
print(x != y)

OUTPUT:
False
True
False
TOPIC 3: PYTHON CONTROL STATEMENTS
PYTHON CONDITIONAL
STATMENTS
• Conditional statements are also known as decision-making
statements. We need to use these conditional statements to
execute the specific block of code if the given condition is
true or false.
• The conditional statements are
1. if statements
2. if-else statements
3. elif statements
4. Nested if and if-else statements
5. elif ladder
• 1) if statements:
• Python if statement is one of the most commonly used
conditional statements in programming languages.
• It decides whether certain statements need to be executed or
not.
• It checks for a given condition, if the condition is true, then
the set of code present inside the ” if ” block will be executed
otherwise not.
• The if condition evaluates a Boolean expression and executes
the block of code only when the Boolean expression becomes
TRUE.
Syntax:
if expression:
statement(s)
____________________________________________________________
If the boolean expression evaluates to TRUE, then the block of
statement(s) inside the if statement is executed.
If boolean expression evaluates to FALSE, then the first set of
code after the end of the if statement(s) is executed.
if Statement Flowchart:
PROGRAM :

a=3
if a > 2:
print(a, "is greater")
print(“Simple if ")

OUTPUT:
3 is greater
2) if-else statements
• The statement itself says if a given condition is true then execute the
statements present inside the “if block” and if the condition is false
then execute the “else” block.
• The “else” block will execute only when the condition becomes
false. It is the block where you will perform some actions when the
condition is not true.
• if-else statement evaluates the Boolean expression. If the condition
is TRUE then, the code present in the “ if “ block will be executed
otherwise the code of the “else“ block will be executed
Syntax:

If (EXPRESSION == TRUE):
Statement (Body of the block)
else:
Statement (Body of the block)
flowchart of if-else
Program:-1
num = 5
if(num > 10):
print(“number is greater than 10”)
else:
print(“number is less than 10”)

print (“This statement will always be executed” )

Output:

number is less than 10.

This statement will always be executed.


Program 2:
a=7
b=0
if (a > b):
print(“a is greater than b”)
else:
print(“b is greater than a”)

Output:

a is greater than b
Program 3:
• Write a python program to print give a number is odd or even
3) elif statements (ladder if)
• In Python, we have one more conditional statement called
“elif” statements. “elif” statement is used to check multiple
conditions only if the given condition is false.
• It’s similar to an “if-else” statement and the only difference is
that in “else” we will not check the condition but in “elif” we
will check the condition.
• “elif” statements are similar to “if-else” statements but “elif”
statements evaluate multiple conditions.
Syntax:

if (condition):
#Set of statement to execute if condition is true
elif (condition):
#Set of statements to be executed when if condition is false and
elif condition is true
else:
#Set of statement to be executed when both if and elif conditions
are false
Flowchart of if – elif - else:
Program1:
num = 10
if (num == 0):
print(“Number is Zero”)

elif (num > 5):


print(“Number is greater than 5”)

else:
print(“Number is smaller than 5”)

Output:

Number is greater than 5


Program 2:
num = -7
if (num > 0):
print(“Number is positive”)
elif (num < 0):
print(“Number is negative”)
else:
print(“Number is Zero”)

Output:

Number is negative
• Program 3:
• Write a python program to implement students grades.
4) Nested if-else statements
• Nested “if-else” statements mean that an “if” statement or “if-
else” statement is present inside another if or if-else block.
Python provides this feature as well, this in turn will help us to
check multiple conditions in a given program.
• An “if” statement is present inside another “if” statement
which is present inside another “if” statements and so on.
Syntax:
if(condition):
#Statements to execute if condition is true
if(condition):
#Statements to execute if condition is true
#end of nested if
#end of if

• The above syntax clearly says that the if block will contain another if
block in it and so on.
• If block can contain ‘n’ number of if block inside it.
Program:
num = 5
if(num >0):
print(“number is positive”)

if(num<10):
print(“number is less than 10”)
Output:

number is positive

number is less than 10


Program :
• Write a python program to display among greatest of three numbers.
TOPIC-4
LOOPS
Loop (or) Iteration
• A loop statement allows us to execute a statement or group of
statements multiple times as long as the condition is true.
Repeated execution of a set of statements with the help of loops is
called iteration.
• Loops statements are used when we need to run same code again
and again, each time with a different value.
• In Python Iteration (Loops) statements are of three types:
• While Loop
• For Loop
• Nested For Loops
1) While loop:
• Loops are either infinite or conditional.
• Python while loop keeps reiterating a block of code defined
inside it until the desired condition is met.
• The while loop contains a Boolean expression and the code
inside the loop is repeatedly executed as long as the Boolean
expression is true.
• The statements that are executed inside while can be a single line
of code or a block of multiple statements.
Syntax:
while(expression):
Statement(s)
Flowchart:
PROGRAM
i=1
while i<=6:
print("Mlritm college")
i=i+1

OUTPUT:
Mlritm college
Mlritm college
Mlritm college
Mlritm college
Mlritm college
Mlritm college
2)For loop:
• The for loop in Python is used to iterate over a sequence
(list, tuple, string) or other iterable objects. Iterating over a
sequence is called traversal.
SYNTAX:

for val in sequence:


loop body
Example Programs:
• 1) for loop using list
list1=[1,2,3]
for x in list1:
print(x)

OUTPUT:
1
2
2
• 2) for loop use tuple:
tuple=(1,2,3)
for x in tuple:
print(x)

Output:
1
2
3
• 3) for loop using dictionary :
x={"csda":204,"csdb":205,"csdc":206}
print("the keys are")
for keys in x:
print(keys)
print("the values are")
for value1 in x.values():
print(value1)
Output:
the keys are
csda
csdb
csdc
the values are
204
205
206
• 4) for loop using String :
x="MLRITM"
for s in x:
print(s)

OUTPUT:
M
L
R
I
T
M
Note: range() function
• The range() function can take 1 to 3 of the following arguments:

• Start: The integer value for the origin of the sequence,


if not passed implicitly it's 0

• Stop: The integer value up to which the sequence will get generated but
won't include this number. This is a required argument which must be passed.

• Step: Establishes the difference between each iteration it can be positive or


negative if not given the default step is 1
Example Programs:
• 1)
for i in range(0, 6, 1):
print(i)

Output:
0
1
2
3
4
5
• 2)
for i in range(6):
print(i)

OUTPUT:
0
1
2
3
4
5
• 3)
for i in range(30,0,-5):
print(i)

OUTPUT:
30
25
20
15
10
5
• 4)
for letter in "Python":
print(letter)

OUTPUT:
P
y
t
h
o
n
5)
for letter in "Python":
print(letter, end=" ")

Output:

Python
3) Nested For loop:
• A nested loop is a loop inside the body of the outer loop. The
inner or outer loop can be any type, such as a while loop or for
loop.
Syntax:
# outer for loop
for element in sequence
# inner for loop
for element in sequence:
body of inner for loop body of outer for loop
Example Programs:
• 1)
x = [1, 2]
y = [4, 5]
for i in x:
for j in y:
print(i, j)
OUTPUT:
14
15
24
25
2)
# Running outer loop from 2 to 3

for i in range(2, 4):

# Printing inside the outer loop


# Running inner loop from 1 to 10
for j in range(1, 11):

# Printing inside the inner loop


print(i, "*", j, "=", i*j)
# Printing inside the outer loop
print()
Output:
2*1=2
2*2=4
2*3=6
2*4=8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
2)
rows = 5
# outer loop
for i in range(1, rows + 1):
# inner loop
for j in range(1, i + 1):
print("*", end=" ")
print('')
OUTPUT:
*
**
***
****
*****
Note:
• Python doesn't have do-while loop. But we can create a program like
this. The do while loop is used to check condition after executing the
statement. It is like while loop but it is executed at least once.
TOPIC-5
PYTHON –BREAK &CONTINUE
• Loops iterate over a block of code until the test expression is false,
but sometimes we wish to terminate the current iteration or even
the whole loop without checking test expression.
1)break
The break statement terminates the loop containing it. Control of the
program flows to the statement immediately after the body of the loop.

If the break statement is inside a nested loop (loop inside another loop),
the break statement will terminate the innermost loop.

Syntax:

break
Flow chart:
The working of break statement in for loop and while loop is shown below.
Program:
• 1)
• # Use of break statement inside the loop
for val in "string":
if val == "i":
break
print(val)
print("The end")

OUTPUT:
s
t
r
The end
• 2) Python continue statement :
• The continue statement is used to skip the rest of the code inside
a loop for the current iteration only.
• Loop does not terminate but continues on with the next iteration.

• Syntax:

• continue
Flow chart:
• Programs:
• The working of the continue statement in for and while loop is shown
below.
• 1) # Program to show the use of continue statement inside loops
for val in "string":
if val == "i":
continue
print(val)
print("The end")

OUTPUT:
s
t
r
n
g
The end
TOPIC :6
Python - List Comprehension
• List comprehension in Python is an easy and compact
syntax for creating a list from a string or another list.
• It is a very concise way to create a new list by performing an
operation on each item in the existing list.
• List comprehension is considerably faster than processing a
list using the for loop.
Syntax:
[expression for element in iterable if condition]
• The above syntax, the list comprehension syntax contains
three parts:
• An expression, one or more for loop, and optionally, one or
more if conditions.
• The list comprehension must be in the square brackets [].
• The result of the first expression will be stored in the new
list.
• The for loop is used to iterate over the iterable object
that optionally includes the if condition.
Example Programs:
1) Create List of Even Numbers with List Comprehension
even_nums = [x for x in range(21) if x%2 == 0]
print(even_nums)

Output:

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]


• 2) List Comprehension with String List:
Program:

list1 = ['Ramu', 'mlritm', '', 'Jai', 'Sai']


list2 = [ s for s in list1 if 'a' in s]
print(list2)

Output:
['Ramu', 'Jai', 'Sai']
a) List Comprehension using Nested Loops
• It is possible to use nested loops in a list comprehension expression.
• In the following example, all combinations of items from two lists
in the form of a tuple are added in a third list object.
• Program :
nums1 = [1, 2, 3]
nums2 = [4, 5, 6]
nums=[(x,y) for x in nums1 for y in nums2]
print(nums)

Output:

[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
b)List Comprehension with Multiple if Conditions
• We can use nested if conditions with a list comprehension.
• Program:
nums = [x for x in range(21) if x%2==0 if x%5==0]
print(nums)

Output:
[0, 10, 20]
c) List Comprehension with if-else Condition
• The following example demonstrates the if..else loop with a list comprehension.
• Program:
odd_even_list = ["Even" if i%2==0 else "Odd" for i in range(5)]
print(odd_even_list)
odd_even_list = [str(i) + '=Even' if i%2==0 else str(i) + "=Odd" for i in range(5)]
print(odd_even_list)

OUTPUT:
['Even', 'Odd', 'Even', 'Odd', 'Even']
['0=Even', '1=Odd', '2=Even', '3=Odd', '4=Even']
TOPIC 7: Python-Generator Expressions
• In Python, to create iterators, we can use both regular
functions and generators.
• Generators are written just like a normal function but we
use yield() instead of return() for returning a result.
• It is more powerful as a tool to implement iterators.
• It is easy and more convenient to implement because it
offers the evaluation of elements on demand.
• Another great advantage of the generator over a list is that it
takes much less memory.
Program:
def simple():
for i in range(10):
if(i%2==0):
yield i

#Successive Function call using for loop


for i in simple():
print(i)
OUTPUT:
0
2
4
6
02468

8
TOPIC 8 : PASS STATEMENT
• In Python programming, the pass statement is a null statement
which can be used as a placeholder for future code.
• Suppose we have a loop or a function that is not implemented yet,
but we want to implement it in the future.
• In such cases, we can use the pass statement.
syntax of pass statement :
PASS
PROGRAM 1 :
x= {"csdc", "csdb", "Pass", "csda"}
for value in x:
if value == "Pass":
pass # leaving an empty if block using the pass keyword
else:
print("Not reached pass keyword: ", value)

• output :
• Not reached pass keyword: csdb
• Not reached pass keyword: csdc
• Not reached pass keyword: csda
PROGRAM 2:
n = 10
# use pass inside if statement
if n > 10:
pass

print('csdc students are very cleavers')

output:

csdc students are very cleavers


TOPIC 9: eval()
• The eval() method parses the expression passed to this
method and runs python expression (code) within the
program.
• Types of eval() parameters.

• The eval() function takes three parameters:


• a)expression - the string parsed and evaluated as a Python
expression
• b)globals (optional) - a dictionary
• c)locals (optional)- a mapping object.
• Dictionary is the standard and commonly used mapping type
in Python.
• Program :

x=1
print(eval('x + 1'))
output:
2

You might also like