Python Statements(Control Flow)
In python, colon and indentation is used in control flow syntax. Indentation is very crucial in python. Let’s have look on various python statements:
if statements
Syntax of if statement:
if condition:
#code #indentation is used here
Syntax of if/else statement:
if condition:
#code #indentation is used here
else:
#code #indentation is used here
If you are using multiple conditions then use elif:
if condition:
#code #indentation is used here
elif condition_1:
#code #indentation is used here
else:
#code #indentation is used here
Let’s see an example:
>>> x = 5
>>> if x < 0:
... print('X is negative')
... elif x == 0:
... print('X is Zero')
... else:
... print('X is positive')
...
X is positive
for Statements
Using for statement, you can iterate over the object. It goes through items that are in a sequence or any other iterable item.
Syntax of for loop:
#numbers.py file
numbers = [1,2,3,4,5,6] #looping over a list
for n in numbers:
print(n)Output:
1
2
3
4
5
6A) How to print even numbers??
-> Add if statement inside a for loop as follows:numbers=[1,2,3,4,5,6] # numbers.py file
for n in numbers:
if n%2 ==0: #checking whether number is divisible by 2 or not
print(n)Output:
2
4
6
looping over a string:
name="ANKIT"
for n in name:
print(n)Output:
A
N
K
I
T
looping over Dictionary:
dict={'john':1,'steve':2,'ricky':3} #dict.py file
for key in dict:
print(key)Output:
john
steve
ricky
This is printing only keys. Then how to produce values or key and value together?
Let’s see:
#print values
dict={'john':1,'steve':2,'ricky':3} #dict.py file
for value in dict.values():
print(value)Output:
2
1
3#print key and value
dict={'john':1,'steve':2,'ricky':3}
for key,value in dict.items():
print(key,value)Output:
john 1
steve 2
ricky 3
Note: Since, Dictionaries are unordered, keys and values come in arbitrary order.
while statements
while loop will continue to execute the code till the condition is true.
Syntax:
while condition:
code text
else:
code text
Let’s see an example:
x=0
while x < 10:
print(x)
x+=1Output:
1
2
3
4
5
6
7
8
9
break and continue statements
break: Breaks out of the current closest enclosing loop.
continue: Goes to the top of the closest enclosing loop.
pass: Does nothing. It can be used when a statement is required syntactically but the program requires no action
break and continue can appear anywhere in the loop body.
for example: in following example, if x equals 5 then execution of while loop will be stopped.
x=0
while x < 10:
print(x)
if x==5:
break
x+=1Output:
1
2
3
4
5# continue statement examplex=0
while x < 10:
x+=1
print(x)
if x==5:
print("Value is 5")
else:
continue #go to the top of the loopOutput:
1
2
3
4
5
value is 5
6
7
8
9
10
That’s it! We have covered the basics for Python statements.
Happy Coding!