If and else statement in Python
If we need to add some conditional statement then we will use if, else conditions.
x = 10
y = 20
if(x < y ):
print("y is greater")
// if and else statement
if(x < y ):
print("y is greater")
else:
print("x is greater")
// if statement with tuple
tup1 = ('a', 'b', 'c')
if('a' in tup1):
print("a is present in tuple")
else:
print("a is not present in tuple")
//if with list
li = [1,2,3]
if(li[1] == 2):
print(2 is present)
else:
print(2 is not present)
// if with dictionary
d = {'apple':10, 'mango': 20, 'kiwi': 30}
if(d['mango'] > 25)
print("Mango price is less then 25")
Loops in Python
While Loop
While loop executes statement repeatedly until condition is true.
i = 1
while i < 10
print(i)
i = i + 1
Output: 1 2 3 4 5 6 7 8 9 10
For Loop
For loop iterate our sequence. Sequence is a list, tuple, dictionary. For is the basic keyword like other programming language.
// Syntax for For loop
for val in sequence:
//body
color_list = ['green', 'yellow', 'red']
for color in color_list
print(color)
Output: green
yellow
red
Nested For Loop
Nested loop means one loop inside another loop
// Syntax for Nested loop
for val in sequence1:
for val in sequence2:
//body
color_list = ['green', 'yellow', 'red']
fruit_list = ['Shirt', 'Paint', 'Top']
for val1 in color_list:
for val2 in fruit_list:
print(val1, val2)
Output:
green Shirt
green Paint
green Top
yellow Shirt
yellow Paint
yellow Top
red Shirt
red Paint
red Top