Control statements in python.
Control statements in python:
The control statements in python are the statements that, are executed sequentially, selectively, or iteratively.
Sequence:
The sequence means the statements are being executed orderly/ sequentially. This represents the default flow of the statements.
Selection:
The selection means the execution of statements depending upon a condition test. If a condition evaluates to TRUE, a set of statements is followed otherwise another set of statements is followed. This construct is also called a decision-making construct.
IF statement:
The simplest form of an if statement is an if-statement. It tests a condition and if the condition evaluates to true, it carries out some instructions. And does nothing in case the condition evaluates to false. Syntax:
if<condition expression>:
[statements]
….
[statements]
Example:
A=int(input("Enter value for A:")) B=int(input("Enter value for B:")) if(A>B): print("A is greater than B ")
Output:
IF ELSE statement:
This form of if statement, tests a condition, and if that condition evaluates to be true, it carries out statements inside the if block. And in case the condition is false, it carries out statements inside the else block.
Syntax:
if<conditional expression>:
[statements]
….
[statements]
else:
[statements]
….
[statements]
Example:
num=int(input("Enter an number")) if num%2==0: print(num,"it is even") else: print(num,"it is odd")
Output:
IF ELIF statement:
It checks some more if-else conditions,
Syntax:
if<conditional expression>:
[statements]
….
[statements]
elif:
[statements]
….
[statements]
else:
[statements]
….
[statements]
Example:
n=int(input("Enter a number:")) if n<0: print(n,"it is negative number") elif n==0: print(n,"its equal") else: print(n,"it is positive number")
Output:
NESTED IF statement:
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.
Syntax:
if<conditional expression>:
if<conditional expression>:
[statements]
….
[statements]
elif:
[statements]
….
[statements]
else:
[statements]
….
[statements]
Iteration:
The iteration constructs mean the repetition of a set of statements depending upon a condition test. Till the condition is true a set of statements are repeated again and again. As soon as the condition becomes false the repetition stops. It is also called a looping statement.
FOR loop:
The for loop of python is designed to process the items of any sequence, such as a list or a string, one by one.
Syntax:
for<variable> in <sequence>:
[statements_to_repeat]
Example:
n=5 for i in range(1,6): print(n,'*',i,'=',n*i)
Output:
WHILE loop:
A while loop is a conditional loop that will repeat the instructions within itself as long as a conditional remains true.
Syntax:
While< logicalexpressions>:
loop_body
Example:
a=5 while a>0: print("hello",a) print("Loop over")
Output:
Also, read check the python code below that doesn’t work properly, adjust it, and explain?