Python: Conditional and Iterative statements
Genrally a program executes its statements from beginning to end. But not many programs execute all their statements in strict order from beginning to end. Programs, depending upon the need, can choose to execute one of the available alternatives or even repeat a set of statements.We will discuss firstly about selection statement if and later iteration statements for and while are discussed.
A pass statement is useful in those instances where the syntax of the language requires the presence of a statement but where the logic of the program does not.
Any single executable statement is a simple statement in Python.
A compund statement represents a group of statements executed as a unt.
In an if statement, if the conditional expression evaluates to true, the statements in the body-of-if are executed .
for e.g.
The if-else statement
An else statement can be combined with an if statement. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value. The else statement is an optional statement and there could be at most only one else statement following if.
Types of statements in Python
1. Empty Statement
pass
A pass statement is useful in those instances where the syntax of the language requires the presence of a statement but where the logic of the program does not.
2. Simple Statement
name = input("Your name")
3. Compound Statement
if True:
print("Hello World")
Statement Flow Control
Sequence
It refers to the normal flow of control in the program
It refers to the normal flow of control in the program
Selection
Iteration (Looping)
The iteration constructs mean repetition of a set-of-statements depending upon a condition-test.
The if statment
The if statment
if <conditional expression> :
statements
In an if statement, if the conditional expression evaluates to true, the statements in the body-of-if are executed .
for e.g.
ch = input("Enter a single caharcter: ")
if ch >='0' and ch <='9':
print("You entered a digit.")
The if-else statement
if <conditional expression> :
statements
else :
statements
An else statement can be combined with an if statement. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value. The else statement is an optional statement and there could be at most only one else statement following if.
num = int ( input("Enter an integer: ")) if num%2 == 0: print(num," is EVEN number") else: print(num," is ODD number")
The if-elif Statement
The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE. Similar to the else, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if.
if sales>=30000:
discount = sales*0.18
elif sales>= 20000:
discount = sales*0.15
else:
discount = sales*0.05
The nested if
A nested if is an if that has another if in its if’s body or in elif’s
body or in its else’s body.
if (conditional expression) :
[statements]
elif (conditional expression) :
[statements]
else :
if (conditional expression) :
statement(s)
else :
statement(s)
The range() function
range(<lower limit>, <upper limit>, <step value>) #all values should be integers
Statement | Values Generated |
---|---|
range(10) | 0,1,2,3,4,5,6,7,8,9 |
range(5,10) | 5,6,7,8,9 |
range(5,15,3) | 5,8,11,14 |
range(10,1,-2) | 10,8,6,4,2 |
Note: In range() function lower limit is included in the list but upper limit is not included in the list.
Operators in and not in
The in operator tests if a given value is contained in a sequence or not and returns True or False accordingly.
Operators in and not in are also called membership operators.
For example,
3 in [1,2,3,4]
will return True as value 3 is contained in sequence [1,2,3,4].
5 in [1,2,3,4]
It will return False as value 5 is not contained in sequence [1,2,3,4]
5 not in [1,2,3,4]
will return True as this fact is true that as value 5 is not contained in sequence [1,2,3,4].
Iteration/Looping Statements
The iteration statements are also called loops or looping statements.
Python provides two kinds of loops: for loop and while loop to represent two categories of loops, which are :
- counting loops - the loops that repeat a certain number of times
- conditional loops - the loops that repeat until a certain thing happens or some condition is true
The for loop
for a in [1,4,7]:
print(a)
print(a*a)
Therefore, the output produced by above for loop will be:
1 1 4 16 7 49 |
for val in range(3,18):
print(val)
In the above loop, range(3,18) will first generate a list [3,4,5, … ,16,17] with which for loop will work.
Program to print table of a number entered by user
num = int(input("Enter the value "))
for a in range(1,11):
print(num,'×',a,'=',num*a)
The while Loop
A while loop is a conditional loop that will repeat the instructions within itself as long as a condition remains true.
a = 5
while a>0:
print("hello",a)
a = a-2
print("Loop Over!")
The above code will print:
hello 5 hello 3 hello 1 Loop Over! |
Jump Statements - break and continue
The break StatementThe break statement enables a program to skip over a part of the code. A break statement terminates the very loop it lies within.
a=2
while True:
print(a)
a*=2
if a < 100:
break
For purposely created infinite (or endless) lops, there must be a provision to reach break statement from within the body of the loop so that loop can be terminated.
The continue statement
The continue statement is another jump statement like the break statement as both the statements skip over a part of the code. But the continue statement is somewhat different from break.
The continue statement skips the rest of the loop statements and causes the next iteration of the loop to take place.
Program to illustrate the difference between break and continue statements.
print("The loop with 'break' produces output as: ")
for i in range(1,11):
if i%3 == 0:
break
else :
print(i)
The output produced by above program is:
1 2 |
print("The loop with 'continue' produces output as: ")
for i in range(1,11):
if i%3 == 0:
continue
else :
print(i)
The output produced by above program is:
1 2 4 5 7 8 10 |
Loop else statement
The loop-else suite executes only in the case of normal termination of loop.
for a in range(1,4):
print("Element is", a)
else:
print("Ending loop after printing all elements of sequence")
The above code will give the following output:
Element is 1 Element is 2 Element is 3 Ending loop after printing all elements of sequence |
Nested Loops
A loop may contain another loop in its body. This form of a loop is called nested loop.
Program to print Star pattern
for i in range(1,6) :
for j in range (1,i) :
print("*",end='')
print()
Ouptut :
* * * * * * * * * * |
No comments: