Python Unit2
Python Unit2
(AUTONOMOUS)
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA
SCIENCE
Unit II -Notes
I YEAR –B.E/B.TECH
(Common to all Branches)
PREPARED BY APPROVED BY
J.PRIYA HOD
1
UNIT II
CONTROL FLOW STATEMENTS
Python interpreter, interactive mode and script mode; variables, expressions, statements;
values and data types; Operators and Precedence of operators, comments; Conditionals:
conditional, alternative, chained conditional, nested conditional; Iterations: while, for,
break, continue.
1. INTRODUCTION TO PYTHON:
Python is a general-purpose interpreted, interactive, object-oriented, and high-
level programming language.
It was created by Guido van Rossum during 1985- 1990.Python got its name from “Monty
Python’s flying circus”. Python was released in the year 2000.
❖ Python is interpreted: Python is processed at runtime by the interpreter. You
do not need to compile your program before executing it.
❖ Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
❖ Python is Object-Oriented: Python supports Object-Oriented style or technique
of programming that encapsulates code within objects.
❖ PythonisaBeginner'sLanguage:Pythonisagreatlanguageforthebeginner-
level programmers and supports the development of a wide range of
applications.
Python Features:
❖ Easy-to-learn: Python is clearly defined and easily readable. The structure
of the program is very simple. It uses few key words.
❖ Easy-to-maintain: Python's source code is fairly easy-to-maintain.
❖ Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
❖ Interpreted: Python is processed at runtime by the interpreter. So, there is no
needtocompileaprogrambeforeexecutingit.Youcansimplyruntheprogram.
❖ Extensible: Programmers can embed python within their C,C++,Javascript
ActiveX, etc.
❖ Free and Open Source: Anyone can freely distribute it, read the source code, and
edit it.
❖ High Level Language: When writing programs, programmers concentrate on
solutions of the current problem, no need to worry about the low level details.
❖ Scalable: Python provides a better structure and support for large programs
than shell scripting.
Applications:
❖ Bit Torrent file sharing
❖ Google search engine, Youtube
❖ Intel, Cisco, HP,IBM
❖ i–Robot
❖ NASA
2
Python interpreter:
Interpreter: To execute a program in a high-level language by translating it one line at a
time.
Compiler: To translate a program written in a high-level language into a low-
level language all at once, in preparation for later execution.
MODES OF PYTHONINTERPRETER:
Python Interpreter is a program that reads and executes Python code. It uses 2 modes
of Execution.
1. Inter active mode
2. Script mode
Interactive mode:
❖ Interactive Mode, as the name suggests, allows us to interact with OS.
❖ When we type Python statement, interpreter displays the result(s)
immediately.
Advantages:
❖ Python, in interactive mode, is good enough to learn, experiment or explore.
❖ Working in interactive mode is convenient for beginners and for testing small
pieces of code.
Drawback:
❖ We cannot save the statements and have to retype all the statements once again to
re-run them.
In interactive mode, you type Python programs and the interpreter displays the result:
>>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you
to enter code. If you type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!')
Hello, World!
This is an example of a print statement. It displays a result on the screen. In this case,
the result is the words.
3
Script mode:
❖ In script mode, type python program in a file and then use interpreter to
execute the content of the file.
❖ Scripts can be saved to disk for future use. Python scripts have
the extension .py, meaning that the filename ends with.py
❖ Save the code with filename.py and run the interpreter in script mode to
execute the script.
4
VARIABLES:
IDENTIFIERS:
Identifier is the name given to entities like class, functions, variables etc. in
Python.
❖ Identifiers can be a combination of letters in lower case(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.
5
❖ Cannot use special symbols like !, @, #, $, % etc. in identifier.
❖ Identifier can be of any length.
Example:
Names like myClass, var_1, and this_is_a_long_variable
Expressions:
-An expression is a combination of values, variables, and operators.
- A value all by itself is considered an expression, and also a variable.
- So the following are all legal expressions:
>>> 42
42
>>>a=2
>>>
a+3+27
>>> z=("hi"+"friend")
>>> print(z)
hifriend
In the above interpreter mode, 5, 15, hello, python, program are the values used
Literal
A literal is a sequence of one or more characters that stands for itself.
Example:12 is a literal. A literal is the way a value of a data type looks to a
programmer. The programmer can use a literal in a program to mention a
data value.
Data type:
Every value in Python has a data type. It is a set of values, and the allowable
operations on those values. For example, the integer data type consists of the
set of integers, and operators for addition, subtraction, multiplication, and
division, among others.
Numbers:
❖ Number data type stores Numerical Values.
❖ This data type is immutable [i.e. values/items cannot be changed].
❖ Python supports integers, floating point numbers and complex numbers.
A numeric literal is a literal containing only the digits 0–9, an optional sign
character ( 1 or 2 ), and a possible decimal point. Number data types store
numeric values. Python supports four different numerical types –
7
➢ int (signed integers)
➢ long (long integers, they can also be represented in octal and hexadecimal)
➢ float (floating point real values)
➢ complex (complex numbers)
9
Sequence:
❖ A sequence is an ordered collection of items, indexed by positive integers.
❖ It is a combination of mutable (value can be changed) and immutable (values
cannot be changed) data types.
❖ There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples
Strings:
A string is a sequence of characters enclosed in matching pain of single or
double quotation marks. A string may contain zero or more characters,
including letters, digits, special characters, and blanks. A string consisting of
only a pair of matching quotes (with nothing in between) is called the empty
string
Examples:
'Hello' 'Smith, John' "Baltimore, Maryland 21210"
Indexing/Accessing Strings:
The characters of the string can be accessed as one character at a time with
the bracket operator and index. In Python, the indexes start from 0: the first
character is at index 0, the second is at index 1, and so on.
Example:
>>> s="python"
>>> print(s)
python
10
>>>
print(s[0])
p
>>> print(s[-1])
n
>>>
Positive indexing helps in accessing the string from the beginning
11
in, not in >>> s="good morning" Using membership operators to
(membership >>>"m" in s check a particular character is in
operator) True string or not. Returns true if
>>> "a" not in s present.
True
OUTPUT:
Output:
"google"
Example's
example
for
vertical
tab
Lists
List is an ordered sequence of items. It is one of the most used datatypes in
Python and is very flexible. All the items in a list do not need to be of the
same type. Items separated by commas are enclosed within brackets [ ].
Operations on list:
Indexing Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion
14
Slicing( ending >>>print(list1[1:3]) - Displaying items from 1st
position-1) [7.79, 101] till2nd.
Slice operator is >>>print(list1[1:]) - Displaying items from
used to extract [7.79, 101, 'hello'] 1stposition till last.
part of a string, or
some part of a list
Python
Concatenation >>>print( list1+list2) -Adding and printing the
['python', 7.79, 101, 'hello', 'god', items of two lists.
6.78, 9]
Repetition >>>list2*3 Creates new strings,
['god', 6.78, 9, 'god', 6.78, 9, 'god', concatenating multiple
6.78, 9] copies of the same string
Updating the list >>>list1[2]=45 Updating the list using index
>>>print( list1) value
[‘python’, 7.79, 45, ‘hello’]
Inserting an >>>list1.insert(2,"program") Inserting an element in 2nd
element >>> print(list1) position
['python', 7.79, 'program', 45,
'hello']
Removing an >>>list1.remove(45) Removing an element by
element >>> print(list1) giving the element directly
['python', 7.79, 'program', 'hello']
Lists are mutable:
Lists are mutable, meaning; value of elements of a list can be altered.
Example:
>>> a = [1,2,3]
>>> a[2]=4
>>> a [1, 2, 4]
# Program To demonstrate lists
>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>
We use keys as index to retrieve the respective value. But values cannot used to
access keys.
18
2.5
>>>str(25)
'25'
Coercion vs. Type Conversion
Coercion is the implicit (automatic) conversion of operands to a common type.
INPUT: Input is data entered by user (end user) in the program. In python, input ()
function is available for input.
Syntax for input() is:
variable = input (“data”)
Example:
>>> x=input("enter the name:")
enter the name: george
>>>y=int(input("enter the number"))
enter the number 3
#python accepts string as default data type. conversion is required for type.
COMMENTS:
A hash sign (#) that is not inside a string literal is the beginning of a
comment. All characters after the #, up to the end of the physical line, are
part of the comment .It extends up to the newline character.
19
Comments are for programmers for better understanding of a program.
Python Interpreter ignores comment.
Example:
OUTPUT:
Multi line comment: The multiple line comments are written using triple
single quotes („ „ „) or triple double quotes(“ “ “)
DOCSTRING:
❖ Docstring is short for documentation string.
❖ It is a string that occurs as the first statement in a module, function, class, or method
definition. We must write what a function/class does in the docstring.
❖ Triple quotes are used while writing docstrings.
❖ Accessing Docstrings: The docstrings can be accessed using the doc method of
the object or using the help function .
Syntax:
Functionname.__doc__
Example:
20
❖ Blocks of code are denoted by line indentation.
❖ It is a space given to the block of codes for class and function definitions or
flow control.
Example:
QUOTATION IN PYTHON:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals.
Anything that is represented using quotations are considered as string.
TUPLE ASSIGNMENT
Example:
-It is useful to swap the values of two variables. With conventional assignment
statements, we have to use a temporary variable. For example, to swap a and b:
(a, b) = (b, a)
-In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the
variables/names on the right:
>>>b = ("George", 25, "20000") # tuple packing
>>>(name, age, salary)=b # tupleunpacking
>>>name
'George'
>>>age
25
>>>salary
'20000'
-The right side can be any kind of sequence (string,list,tuple)
22
Example:
-To split an email address in to user name and a domain
>>> mailid='[email protected]'
>>> name,domain=mailid.split('@')
>>> print (name)
god
>>> print (domain)
abc.org
OPERATORS:
❖ Operators are the constructs which can manipulate the value of operands.
❖ Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and +
is called operator.
❖ Types of Operators:
-Python language supports the following types of operators
• Arithmetic Operators
• Comparison (Relational)Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Arithmetic operators:
Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication etc.
Arithmetic operators in Python
Operator Meaning Example
+ Add two operands or unary plus x+y
- Subtract right operand from the left or unary minus x-y
* Multiply two operands x*y
/ Divide left operand by the right one (always results into float) x/y
% Modulus - remainder of the division of left operand by the right x%y
(remainder of x/y)
// Floor division - division that results into whole number adjusted x // y
to the left in the number line
** Exponent - left operand raised to the power of right x**y
(x to the power y)
g=x**y
print("The exponentiation is:",g)
OUTPUT:
Comparison (Relational)Operators:
• Comparison operators are used to compare values.
• It either returns True or False according to the condition. Assume, a=10 and b=5
> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.
< If the value of left operand is less than the value of right (a < b) is
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. not true.
24
<= If the value of left operand is less than or equal to the value (a <= b) is
of right operand, then condition becomes true. true.
Example
a=10 Output:
b=5 a>b=> True
print("a>b=>",a>b) a>b=> False
print("a>b=>",a<b) a==b=> False
print("a==b=>",a==b) a!=b=> True
print("a!=b=>",a!=b) a>=b=> False
print("a>=b=>",a<=b) a>=b=> True
print("a>=b=>",a>=b)
Assignment Operators:
-Assignment operators are used in Python to assign values to variables.
Operator Description Example
+= Add AND It adds right operand to the left operand and assign c += a is
the result to left operand equivalent
to c = c +a
25
**= Exponent Performs exponential (power) calculation on c **= a is
AND operators and assign value to the leftoperand equivalent
to c = c ** a
Logical Operators:
-Logical operators are the and, or, not operators.
Example Output
a = True x and y is False
b = False x or y is True
print('a and b is',a and b) not x is False
print('a or b is',a or b)
print('not a is',not a)
26
Truth tables for And ,or ,not
Truth table for or
Truth table for and
A B A or B
A B A and B
True True True True True True Truth table for
True False False True False True not
False True False A not A
False True True
False False False True False
False False False
Bitwise Operators:
• A bitwise operation operates on one or more-bit patterns at the level of
individual bits
Example: Let x = 10 (0000 1010 in binary) and
y = 4 (0000 0100 in binary)
Example:
#To demonstrate bitwise operators
x=10
y=12
print("The bitwise and is:",x&y)
print("The bitwise or is:",x|y)
print("The bitwise xor is:",x^y)
print("The bitwise not is:",~x)
print("The bitwise left shift by 2 positions is:",x<<2)
print("The bitwise right shift by 2 positions is:", x>>2)
OUTPUT:
The bitwise and is: 8 The
bitwise or is: 14 The
bitwise xor is: 6 The
bitwise not is: -11
The bitwise left shift by 2 positions is: 40
The bitwise right shift by 2 positions is: 2
Membership Operators:
Identity Operators:
❖ They are used to check if two values (or variables) are located on the same
part of the memory.
Example
x =5 Output
y =5 False
x2 = 'Hello' True
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description
28
+- Addition and subtraction
29
a=2,b=12,c=1 a=2*3+4%5-3//2+6
d=a<b>c a=2,b=12,c=1 a=6+4-1+6
d=2<12>1 d=a<b>c-1 a=10-1+6
d=1>1 d=2<12>1-1 a=15
d=0 d=2<12>0
d=1>0
d=1
Associativity of operators:
Associativity decides the order in which the operators with same precedence are executed.
There are two types of associativity:
Left-to-right: In left-to-right associativity, the operator of same precedence are executed from
the left side first. Eg:*, // are examples for left to right associative operators
Right-to-left: In right-to-left associativity, the operator of same precedence are executed from
right side first. Eg: ** is right to left associative
Example:
>>> 3*4//6 2
>>> 3*(4//6) 0
>>> 3**4**2 43046721
>>> (3**4)**2 6561
>>>
Control flow is the order that instructions are executed in a program. A control
statement is a statement that determines the control flow of a set of instructions.
There are three fundamental forms of control that programming languages provide-
sequential control , selection control , and iterative control
Sequential control is an implicit form of control in which instructions are executed in
the order that they are written. A program consisting of only sequential control is
referred to as a ―straight- line program
Selection control is provided by a control statement that selectively executes instructions
Iterative control is provided by an iterative control statement that repeatedly
executes instructions. Each is based on a given condition.
30
CONDITIONALS
The conditional statements are the statements that alter the flow of execution of the
program based on a condition. These statements decide upon the result of test
condition and execute certain set of statements. These are known as selection or
decision making or branching statements or conditional statements
Conditional(if):
conditional (if) is used to test a condition, if the condition is true the statements
inside if will be executed.
syntax:
Flowchart:
Example:
1. Program to provide flat Rs 500, if the purchase amount is greater than2000.
2. Program to provide bonus mark if the category is sports.
31
Program to provide bonus mark if the category is sports output
m=int(input(“enter ur mark out of 100”)) enter ur mark out of
c=input(“enter ur categery G/S”) 100 85
if(c==”S”): enter ur categery G/S
m=m+5 S
print(“mark is”,m) mark is 90
Conditional(if-else)
In the alternative the condition must be true or false. In this else statement can be
combined with if statement. The else statement contains the block of code that executes
when the condition is false. If the condition is true statements inside the if get executed
otherwise else part gets executed. The alternatives are called branches, because they are
branches in the flow of execution.
syntax:
Flowchart:
Examples:
1. odd or even number
2. positive or negative number
3. leap year or not
4. greatest of two numbers
5. eligibility for voting
Chained conditionals(if-elif-else)
• The elif is short for elseif.
• This is used to check more than one condition.
• If the condition1 is False, it checks the condition2 of the elif block. If all the
conditions are False, then the else part is executed.
• Among the several if...elif...else part, only one part is executed according to
the condition.
• The if block can have only one else block. But it can have multiple elif blocks.
• The way to express a computation like that is a chained conditional.
syntax:
33
Flowchart:
Example:
1. student mark system
2. traffic light system
3. compare two numbers
4. roots of quadratic equation
student mark system Output
mark=int(input("enter ur mark:")) enter ur mark:78
if(mark>=90): grade:B
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
traffic light system Output
colour=input("enter colour of light:") enter colour of light:green
if(colour=="green"): GO
print("GO")
elif(colour=="yellow"):
print("GET READY")
else:
print("STOP")
34
compare two numbers Output
x=int(input("enter x value:")) enter x value:5
y=int(input("enter y value:")) enter y value:7
if(x == y): x is less than y
print("x and y are equal")
elif(x < y):
print("x is less than y")
else:
print("x is greater than y")
Nested conditionals
One conditional can also be nested within another. Any number of condition can be
nested inside one another. In this, if the condition is true it checks another if condition1.
If both the conditions are true statement1 get executed otherwise statement2 get
execute. if condition is false statement3 gets executed
Syntax:
35
Flowchart:
Example:
1. greatest of three numbers
2. positive negative or zero
36
ITERATION:
The process of repeated execution of a set of statements is called iteration or looping
.Python has two statements for iteration.
• while
• for
state
while
for
State:
Transition from one process to another process under specified condition with in a
time is called state.
Whileloop:
• While loop statement in Python is used to repeatedly executes set of
statement as long as a given condition istrue.
• In while loop, test expression is checked first. The body of the loop is entered
only if the test expression is True. After one iteration, the test expression is
checked again. This process continues until the test expression evaluates
toFalse.
• In Python, the body of the while loop is determined throughindentation.
• The statements inside the while start with indentation and the first
unindented line marks the end.
Syntax:
Flowchart:
37
❖ The statements inside for loop and statements inside else will also execute.
Program output
i=1 1
while(i<=5): 2
print(i) 3
i=i+1 4
else: 5
print("the number greater than 5") the number greater than 5
Nested while:
• While inside another while is called nested while
• The syntax for a nested while loop statement in Python programming language is
as follows
• Syntax
While condition1:
while
condition2:
statement2(
s) statement1(s)
Nested While( to multiply numbers):
i=1 4
while 5
i<4: 8
j=4 10
while j<6: 12
print(i*j) 15
j=j+1
i=i+1
Examples:
1. program to find sum of n numbers:
2. program to find factorial of a number
3. program to find sum of digits of a number:
4. Program to Reverse the given number:
5. Program to find number is Armstrong number or not
6. Program to check the number is palindrome or not
Sum of n numbers: output
n=int(input("enter n")) enter n
i=1 10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)
38
Factorial of a numbers: output
n=int(input("enter n")) enter n
i=1 5
fact=1 120
while(i<=n):
fact=fact*i
i=i+1
print(fact)
Sum of digits of a number: output
n=int(input("enter the number")) enter a
sum1=0 number 123
while n>0: 6
d=n%10
sum1=sum1+
d n=n//10
print(sum1)
Reverse the given number: output
n=int(input("enter the number")) enter a number
rev=0 123
while n>0: 321
d=n%10
rev=(rev*10)+d
n=n//10
print(rev)
Armstrong number or not output
n=int(input("enter the number")) enter a number153
arm=0 The given number is Armstrong number
temp=n
while temp>0:
d=temp%10
arm=arm+(d**3)
temp=temp//10
if n==arm:
print(n,"is a armstrong number")
else:
print(n,"is not armstrong")
39
Palindrome or not output
n=int(input("Enter a number:")) enter a number121
temp=n The given no is palindrome
reverse=0
while(n>0):
d=n%10
reverse=(reverse*10)+d
n=n//10
if(temp==reverse):
print("The number is palindrome")
else:
print("The number is not palindrome")
For loop:
For in sequence
❖ The for loop in Python is used to iterate over a sequence (list, tuple, string).
Iterating over a sequence is called traversal. Loop continues until we reach the
last element in the sequence.
❖ The body of for loop is separated from the rest of the code using indentation.
o
n
2
2. For loop in list for i in [2,3,5,6,9]: 3
print(i) 5
6
9
for i in (2,3,1): 2
3. For loop in tuple print(i) 3
1
40
❖ for in range:
- can generate a sequence of numbers using range() function. range(10)
will generate numbers from 0 to 9 (10 numbers).
❖ In range function have to define the start, stop and step size
as range(start,stop,step size). step size defaults to 1 if not provided.
syntax
Flowchart:
Nested for:
• for inside another for is called nested for
• The syntax for a nested for loop statement in Python programming language is as
follows
• Syntax
41
example output
for i in range(1,4): 4
for j in range(4,7): 5
print(i*j) 6
8
10
12
12
15
18
Examples:
1. print nos divisible by 5 not by10:
2. Program to print Fibonacci series.
3. Program to find factors of a given number
4. check the given number is perfect number or not
5. check the no is prime or not
6. Print first n prime numbers
7. Program to print prime numbers in range
42
find factors of a number Output
43
Program to print prime numbers in range output:
lower=int(input("enter a lower range")) enter a lower
upper=int(input("enter a upper range")) range5 enter a
for n in range(lower,upper + 1): upper range15 5
if n > 1: 7
for i in range(2,n): 11
if (n % i) == 0: 13
break
else:
print(n)
where
• stop is the required parameter.
• The start specifies where to start the range. The default value is0.
• The step specifies the step between each number. The default is1.
• All parameters are integers
• All parameters can be positive or negative
xrange():
This function works similar to range().This function returns the generator object
that can be used to display numbers only by looping. Only particular range is
displayed on demand and hence called―lazy evaluation―.
Syntax:
xrange([start],stop,[step])
where
• stop is the required parameter.
• The start specifies where to start the range. The default value is0.
• The step specifies the step between each number. The default is1.
• All parameters are integers
• All parameters can be positive or negative
Difference between range() and xrange():
OUTPUT:
5
7
9
Loop Control Structures
Loops iterate over a block of code until test expression is false. The statements
that are used to terminate the current iteration or even the whole loop without
checking test expression
The following are the loop control statements in python:
• break
• continue
• pass
45
BREAK
❖ Break statements can alter the flow of a loop.
❖ It terminates the current loop and executes the remaining statement outside the
loop.
❖ If the loop has else statement, that will also gets terminated and come out of the
loop completely.
Syntax:
break
Flowchart
example Output
for i in w
"welcome": e
if(i=="c"): l
brea
k
print(i)
CONTINUE
It terminates the current iteration and transfer the control to the next iteration in th e
loop.
Syntax:Continue
46
Flowchart
Example: Output
for i in "welcome": w
if(i=="c"): e
continue l
print(i) o
m
e
PASS
It is used as a placeholder for future implementation of functions, loops, etc. In Python
programming, pass is a null statement. The difference between a comment and pass
statement in Python is that, while the interpreter ignores a comment entirely, pass is not
ignored. However, nothing happens when pass is executed. It results into no operation
(NOP).
Syntax:
Pass
47
Example Output
for i in w
“welcome”: if (i e
== “c”): l
pas c
s o
print(i) m
e
48