Unit 2
Unit 2
Unit-2
Python Programming
Subject Code : KNC-402
Unit-2
Syllabus
Statement 1
Statement 2
Statement 3
……..
……..
……..
1. SEQUENCE – FLOW CHART
Statement 1
Statement 2
Statement 3
2. SELECTION
SELECTION
2. SELECTION
• True and False are special values that belong to the class bool ; they are not strings:
• Although these operations are probably familiar to you, the Python symbols are different
from the mathematical symbols for the same operations.
if x < y: 6 10
print (x)
else:
print (y) Output
print (‘is the min’) 6
20-10-2023 Python Programming 14
If Statement
Example:
15
Conditional Execution
• If you enter an if statement in the Python
interpreter, the prompt will change from three
chevrons to three dots to indicate you are in the
middle of a block of statements, as shown below:
This error is called the Indentation Error. Since there is no { } (curly brackets) to show the start and
end of a block, Python uses the indented line (generally 4 spaces or a tab space) to identify it.
if boolean-expr :
S1
S2
S1
• Execution of if statement S2
• Since the condition must either be true or false, exactly one of the alternatives will be
executed.
19
• General form of the if-else statement
if boolean-expr :
S1
else: S1 S2
S2
S3 S3
Type 1 Type 2
if a <= b:
if a <= c:
…
else:
…
else:
if b <= c) :
…
else:
…
22
23
Program Output
24
Chained conditionals (If-Elif ladder)
• Sometimes there are more than two possibilities, and we need more than two branches.
One way to express a computation like that is a chained conditional:
: Colon Must
if first condition:
first body
elif second condition:
second body
elif third condition:
third body
else:
fourth body
If-elif-else Statement
Python supports if-elif-else statements to test additional conditions apart from the initial test expression.
The if-elif-else construct works in the same way as a usual if-else statement. If-elif-else construct is also
known as nested-if construct.
Example:
28
If-elif-else Statement
• A special kind of nesting is the chain of if-else-if-
else-… statements
• Can be written elegantly using if-elif-..-else
if cond1: if cond1:
s1 s1
else: elif cond2:
if cond2: s2
s2 elif cond3:
else: s3
if cond3: elif …
s3 else
else: last-block-of-stmt
EXAMPLES – if elif STATEMENT
READ AS
18 is less
than age
and
18 is less
than 60
OUTPUT
Expressions
An expression is any legal combination of symbols (like variables, constants and operators) that
represents a value. In Python, an expression must have at least one operand (variable or constant) and
can have one or more operators. On evaluating an expression, we get a value. Operand is the value on
which operator is applied.
Constant Expressions: One that involves only constants. Example: 8 + 9 – 2
Integral Expressions: One that produces an integer result after evaluating the expression. Example:
a = 10
• Floating Point Expressions: One that produces floating point results. Example: a * b / 2
• Relational Expressions: One that returns either true or false value. Example: c = a>b
• Logical Expressions: One that combines two or more relational expressions and returns a value as True
or False. Example: a>b && y! = 0
• Bitwise Expressions: One that manipulates data at bit level. Example: x = y&z
• Assignment Expressions: One that assigns a value to a variable. Example: c = a + b or c = 10
31
Expression Evaluation in Python
Program Output
# Python Program to find Largest of Two Numbers
a = float(input(" Please Enter the First Value a: "))
b = float(input(" Please Enter the Second Value b: "))
Program
Output
How many terms?
10
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
3. ITERATION OR LOOPING
ITERATION
3. ITERATION OR LOOPING
while loop
for loop
Control Statement in Python
Control Statement in Python
WHILE LOOP
FLOW CHART
WHILE LOOP
While Loop
Example:
44
While Loop with Else
45
While Loop with Else Flowchart
46
While Loop with Else
Program
i=0
while i < 4:
i += 1
print(i)
else: # Executed because no break in for
print("No Break\n")
i=0
while i < 4:
i += 1
print(i)
break
else: # Not executed as there is a break
print("No Break")
47
Infinite While Loop
48
Nested While Loop
49
Nested While Loop
Program Output
50
Condition-controlled and Counter-controlled Loops
51
Range Function
Range function
• To iterate over a sequence of numbers, the built-in function range() comes in
handy. It generates arithmetic progressions. For example, if we want to print a
whole number from 0 to 10, it can be done using a range(11) function in a for loop.
• In a range() function we can also define an optional start and the endpoint to the
sequence. The start is always included while the endpoint is always excluded.
Starting point
Example:
for i in range(1, 6):
print("Hello World!") Ending point
• Example:
Step size
• for i in range(0,20, 2):
print(i)
For loop provides a mechanism to repeat a task until a particular condition is True. It is usually known as a
determinate or definite loop because the programmer knows exactly how many times the loop will repeat.
The for...in statement is a looping statement used in Python to iterate over a sequence of objects.
59
Example This is actually a temporary
variable which store the
number of iteration
Code:
for i in range(6): Number of times you want to
print(“Hello World!”) execute the statement
Output:
print(“Hello World!”)
print(“Hello World!”)
print(“Hello World!”)
print(“Hello World!”)
print(“Hello World!”)
For Loop Range() Function
The range() function is a built-in function in Python that is used to iterate over a sequence of numbers. The
syntax of range() is range(beg, end, [step])
The range() produces a sequence of numbers starting with beg (inclusive) and ending with one less than
the number end. The step argument is option (that is why it is placed in brackets). By default, every
number in the range is incremented by 1 but we can specify a different increment using step. It can be
both negative and positive, but not zero.
Examples:
61
for LOOP - range KEYWORD
Examples:
63
Else statement in For Loop
Else Can Be Used In For Loop .The Else Body Will Be Executed As And When The
Loop’s Conditional Expression Evaluates To False
for x in range(6):
print(x)
else:
print("Finally finished!")
64
Else statement in For Loop
Else Can Be Used In For Loop .The Else Body Will Be Executed As And When The
0
Loop’s Conditional Expression Evaluates To False
1
2
Program
3 Output
4
for x in range(6):
5 0
Finally finished! 1
print(x) 2
else: 3
4
print("Finally 5
finished!") Finally finished!
65
Nested For Loop
A Loop inside a loop is Known as a nested Loop In the nested loop, the
number of iteration will be equal to the number of iteration in the outer loop
multiplied by the iteration in the inner Loop
66
Nested For Loop
• Python allows its users to have nested loops, that is, loops that can be placed inside other
loops. Although this feature will work with any loop like while loop as well as for loop.
• A Loop inside a loop is Known as a nested Loop In the nested loop, the number of iteration
will be equal to the number of iteration in the outer loop multiplied by the iteration in the
inner Loop
• A for loop can be used to control the number of times a particular set of statements will be
executed. Another outer loop could be used to control the number of times that a whole
loop is repeated.
• Loops should be properly indented to identify which statements are contained within each
for statement.
67
Nested For Loop with Output
Python Program to Print Natural Numbers using For Loop
Program Output
# Python Program to Print Natural Numbers from 1 to N
number = int(input("Please Enter any Number: "))
70
71
72
73
Harbhajan
H A R B H A J A N
Accessing Character And String
Output
Accessing Character with – Indexing
Output
78
79
80
Accessing List Using For Loop
81
List Are Mutable
Access the List Using for Loop
5
for i in [5, 4, 3, 2, 1] : 4
print(i) 3
print('Blastoff!')
2
1
Blastoff!
Accessing Dictionary Using For Loop
88
Dictionary
Python’s dictionaries stores data in key-value pairs. The key values are usually strings and
value can be of any data type. The key value pairs are enclosed with curly braces ({ }). Each key
value pair separated from the other using a colon (:). To access any value in the dictionary, you
just need to specify its key in square braces ([]).Basically dictionaries are used for fast retrieval
of data
Example:
89
Dictionaries
• In dictionaries:
• Can contain any and different types of elements (i.e., keys and values)
• Can contain only unique keys but duplicate values
• CANNOT be concatenated
• CANNOT be repeated
• Can be nested (e.g., d = {"first":{1:1}, "second":{2:"a"}}
• Can be indexed but only through keys (i.e., dic2[“a”] will return 1 but dic2[0] will
return an error since there is no element with key 0 in dic2 above)
Accessing Values in Dictionary:
• To access dictionary elements, you use the familiar square brackets along with
the key to obtain its value:
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class':
'First'};
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];
• This will produce following result:
dict['Name']: Zara
dict['Age']: 7
Loop Through Dictionaries
• In dictionaries:
• Can be iterated over Output:
dic = {“Brand":1, “Model": 2, “Year": 22} Brand
for i in dic: ONLY the keys will be returned.
Model How to get the values?
print(i) Year
Or
1. break STATEMENT
2. continue STATEMENT
Write a PYTHON program to print star Pattern
Program
Output
for i in range(1,5):
for j in range(1,5):
if(j<=i):
print("*",end='')
else:
print("",end='')
print()
1. break STATEMENT
• Break can be used to unconditionally jump out of the loop. It terminates the
execution of the loop. Break can be used in while loop and for loop. Break is
mostly required, when because of some external condition, we need to exit
from a loop.
• When compiler encounters a break statement, the control passes to the
statement that follows the loop in which the break statement appears.
1. break STATEMENT
Loop
Condition ? break
causes
jump
True
Statement 1
break
1. break STATEMENT
• Break can be used to unconditionally jump out of the loop. It terminates the
execution of the loop. Break can be used in while loop and for loop. Break is
mostly required, when because of some external condition, we need to exit
from a loop.
• When compiler encounters a break statement, the control passes to the
statement that follows the loop in which the break statement appears.
2. continue STATEMENT
The continue statement in Python returns the control to the beginning of the while loop.
The continue statement rejects all the remaining statements in the current iteration of
the loop and moves the control back to the loop-continuation portion of the nearest
enclosing loop. The continue statement can be used in both while and for loops
2. continue STATEMENT
Loop False
Condition ?
True
Statement 1
Statements
ignored or continue
skipped
continue
Statement n
causes
jump
2. continue STATEMENT
2. continue STATEMENT
Program
numbers = [2, 3, 11, 7]
for i in numbers:
print('Current Number is', i)
# skip below statement if number is greater
than 10
if i > 10:
continue
square = i * i
print('Square of a current number is', square)
pass STATEMENT
The pass statement in Python is used when a statement is required syntactically but you do not want
any command or code to execute. It specified a null operation or simply No Operation (NOP)
statement. Nothing happens when the pass statement is executed.
The pass is also useful in places where your code will eventually go, but has not been written yet (e.g.,
in stubs for example):
Difference between comment and pass statements In Python programming, pass is a null statement.
The difference between a comment and pass statement is that while the interpreter ignores a comment
entirely, pass is not ignored. Comment is not executed but pass statement is executed but nothing
happens.
pass STATEMENT
pass STATEMENT
A pass statement is a Python null statement. When the interpreter finds a pass
statement in the program, it returns no operation. Nothing happens when
the pass statement is executed.
Program
if 5>2 :
pass
else:
print("Else Part")
print("Rest of the code")
Difference Between break and continue
break continue
Difference Between break and continue
BREAK CONTINUE
It terminates the execution of It terminates only the current iteration of
remaining iteration of the loop. the loop.
'break' resumes the control of the 'continue' resumes the control of the
program to the end of loop enclosing program to the next iteration of that loop
that 'break'. enclosing 'continue'.
It causes early termination of loop. It causes early execution of the next
iteration.
'break' stops the continuation of 'continue' do not stops the continuation
loop. of loop, it only stops the current
iteration.
For loop – Programs - Home Work