[go: up one dir, main page]

0% found this document useful (0 votes)
14 views108 pages

Unit 2

Uploaded by

Harsh Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views108 pages

Unit 2

Uploaded by

Harsh Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 108

Python Programming

Unit-2
Python Programming
Subject Code : KNC-402
Unit-2
Syllabus

Conditionals: Conditional statement in Python (if-else statement, its


working and execution), Nested-if statement and Elif statement in
Python, Expression Evaluation & Float Representation.

Loops: Purpose and working of loops , While loop including its


working, For Loop , Nested Loops , Break and Continue.
.
INTRODUCTION

Programs are written for the solution to the real world


problems. A language should have the ability to control the flow of
execution so that at different intervals different statements can be
executed. Structured programming is a paradigm aims at controlling
the flow of execution of statements in a program by using control
structures.
A language which supports the control structures is called as
structured programming language
Control Statements

A control statement is a statement that determines the control flow of a set of


instructions, i.e., it decides the sequence in which the instructions in a
program are to be executed.

Types of Control Statements —


• Sequential Control: A Python program is executed sequentially from the
first line of the program to its last line.
• Selection Control: To execute only a selected set of statements.
• Iterative Control: To execute a set of statements repeatedly.
4
1. SEQUENCE

Sequence is the default control structure; instructions are


executed one after another.

Statement 1
Statement 2
Statement 3
……..
……..
……..
1. SEQUENCE – FLOW CHART

Statement 1

Statement 2

Statement 3
2. SELECTION

SELECTION
2. SELECTION

A selection statement causes the program


control to be transferred to a specific flow based
upon whether a certain condition is true or not.
Conditional Execution (If)

•In daily routine


• If it is very hot, I will skip exercise.
• If there is a quiz tomorrow, I will
first study and then sleep.
Otherwise, I will sleep now.
• If I have to buy coffee, I will
go left. Else I will go
straight.
20-10-2023 Python Programming 9
Conditional Execution (If)
• In order to write useful programs, we almost always need the ability to check conditions
and change the behavior of the program accordingly.
• Conditional statements give us this ability.
• The simplest form is the if statement:

20-10-2023 Python Programming 10


Boolean Expressions ()
• A boolean expression is an expression that is either true or false. The following examples
use the operator ==, which compares two operands and produces True if they are equal
and False otherwise:

• True and False are special values that belong to the class bool ; they are not strings:

20-10-2023 Python Programming 11


Boolean Expressions
• The == operator is one of the comparison operators; the others are:

• Although these operations are probably familiar to you, the Python symbols are different
from the mathematical symbols for the same operations.

20-10-2023 Python Programming 12


Logical operators
• There are three logical operators: and, or, and not. The semantics (meaning) of these
operators is like their meaning in English. For example,
• x > 0 and x < 10
• is true only if x is greater than 0 and less than 10.
• n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that is, if the number is
divisible by 2 or 3.
• Finally, the not operator negates a boolean expression, so not (x > y) is true if x > y is
false; that is, if x is less than or equal to y.
• Strictly speaking, the operands of the logical operators should be boolean expressions,
but Python is not very strict. Any nonzero number is interpreted as “true.”

20-10-2023 Python Programming 13


• Indentation is important in Python
• grouping of statement (block of statements)
• no explicit brackets, e.g. { }, to group statements

x,y = 6,10 Run


x the program
y

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:

• When using the Python interpreter, you must leave


a blank line at the end of a block, otherwise Python
will return an error:

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.

20-10-2023 Python Programming 16


• General form of the if statement

if boolean-expr :
S1
S2
S1

• Execution of if statement S2

• First the expression is evaluated.


• If it evaluates to a true value, then S1 is executed and
then control moves to the S2.
• If expression evaluates to false, then control moves to
the S2 directly.

20-10-2023 Python Programming 17


If-Else Conditional Statement
• A second form of the if statement is alternative execution, in which there are two
possibilities, and the condition determines which one gets executed. The syntax looks
like this:
If-Else Conditional Statement
• A second form of the if statement is alternative execution, in which there are two
possibilities, and the condition determines which one gets executed. The syntax looks
like this:

• 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

• Execution of if-else statement


• First the expression is evaluated.
• If it evaluates to a true value, then S1 is executed and
then control moves to S3.
• If expression evaluates to false, then S2 is executed and
then control moves to S3.
• S1/S2 can be blocks of statements!
20-10-2023 Python Programming 20
if-else statement
• Compare two integers and print the min.

if x < y: 1. Check if x is less


print (x) than y.
2. If so, print x
else: 3. Otherwise, print y.
print (y)
print (‘is the minimum’)

20-10-2023 Python Programming 21


Nested If Else Statement

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:

• elif is an abbreviation of “else if”.


• Again, exactly one branch will be executed.

20-10-2023 Python Programming 25


Chained conditionals (If-Else ladder)
• There is no limit on the no. of elif statements. If there is an else clause, it must be at the
end, but there doesn’t have to be one.

20-10-2023 Python Programming 26


CONDITIONAL CONSTRUCT – if elif else STATEMENT

: 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

• A Python program contains one or more statements. A statement contains zero or


more expressions. Python executes a statement by evaluating its expressions to
values one by one. Python evaluates an expression by evaluating the sub-
expressions and substituting their values.
• Actions Performed in Python in Two Forms
• Expression Evaluation
• Statement execution
• The key difference between these two forms is that expression evaluation returns
a value whereas statement execution does not return any value
• A Python program contains one or more statements. A statement contains zero or
more expressions. Python executes a statement by evaluating its expressions to
values one by one.
Float Representation in Python
PROGRAM LIST ON if CONTSTUCT

1. Write a PYTHON program that reads a value of n and


check the number is zero or non zero value.
2. Write a PYTHON program to find a largest of two
numbers.
3. Write a PYTHON program that reads the number and
check the no is positive or negative.
4. Write a PYTHON program to check entered character is
vowel or consonant.
Write a PYTHON program to find a largest of two numbers

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: "))

if(a > b):


print("{0} is Greater than {1}".format(a, b))
elif(b > a):
print("{0} is Greater than {1}".format(b, a))
else:
print("Both a and b are Equal")
Write a Python Program to Print the Fibonacci sequence for N terms

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

What is loop or iteration?

Loops can execute a block of code number of times until a


certain condition is met.
OR
The iteration statement allows instructions to be executed until
a certain condition is to be fulfilled.
The iteration statements are also called as loops or Looping
statements.
3. ITERATION OR LOOPING

Python provides two kinds of loops & they are,

while loop

for loop
Control Statement in Python
Control Statement in Python
WHILE LOOP

A while loop allows general repetition based


upon the repeated testing of a Boolean condition

The syntax for a while loop in Python is as follows:


while condition:
body : Colon Must
Where, loop body contain the single statement or
set of statements (compound statement) or an empty
statement.
WHILE LOOP

The loop iterates while the expression evaluates


to true, when expression becomes false the loop
terminates.

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

Output: Prints Hello World! five times


Range function
Range function
• The range() function also takes in another optional parameter i.e. step size. Passing
step size in a range() function is important when you want to print the value uniformly
with a certain interval.
• Step size is always passed as a third parameter where the first parameter is the
starting point and the second parameter is the ending point. And if the step_size is not
provided it will take 1 as a default step_size.

• Example:
Step size
• for i in range(0,20, 2):
print(i)

Output: prints all the even numbers till 20


Range function
Rules for Range function
FOR LOOP

Python’s for-loop syntax is a more convenient


alternative to a while loop when iterating through a
series of elements. The for-loop syntax can be used on
any type of iterable structure, such as a list, tuple str,
set, dict, or file
Syntax or general format of for loop is,

for element in iterable:


body
For Loop

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

The range() function returns a sequence of numbers, starting


from 0 by default, and increments by 1 (by default), and ends at a
specified number.

range(start, stop, step)

for n in range(3,6): x = range(3, 6)


print(n) OR for n in x:
print(n)
Range() Function in For Loop
If range() function is given a single argument, it produces an object with values from 0 to argument-1. For
example: range(10) is equal to writing range(0, 10).
• If range() is called with two arguments, it produces values from the first to the second. For example,
range(0,10).
• If range() has three arguments then the third argument specifies the interval of the sequence produced. In
this case, the third argument must be an integer. For example, range(1,20,3).

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: "))

print("The List of Natural Numbers from 1 to {0}


are".format(number))

for i in range(1, number + 1):


print (i, end = ' ')
Accessing Strings Using For Loop

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

friends = ['Joseph', 'Glenn',


'Sally']
for i in friends :
print('Happy New Year:', i) Happy New Year: Joseph
print('Done!') Happy New Year: Glenn
Happy New Year: Sally
Done!
z = ['Joseph', 'Glenn', 'Sally']
for x in z:
print('Happy New Year:', x)
print('Done!')
Accessing 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"}}

dic2 = {"a":1, "a":2, "b":2} Output: {'a': 2, 'b': 2}


print(dic2)

The element “a”:2 will override the element “a”:1


because only ONE element can have key “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

dic1 = {"first": 1, "second": 2, "third": 3} 1


for i in dic: 2 ONLY the value will be returned.
print(dict1[i]) 3
Write a PYTHON program to print star Pattern
Program
Output
rows = 5
1
for i in range(1, rows + 1):
12
for j in range(1, i + 1): 123
print(j, end=' ') 1234
print('') 12345
4. BRANCHING OR JUMPING STATEMENTS

Python has an unconditional branching statements


and they are,

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.

It is useful in a situation where we are implementing new methods or also in


exception handling. It plays a role like a placeholder.

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

1. Write a PYTHON program to print the natural numbers


up to n
2. Write a PYTHON program to print even numbers up to
n
3. Write a PYTHON program to print odd numbers up to n
4. Write a PYTHON program that prints 1 2 4 8 16 32 …
n2

You might also like