I
F...ELSE, WHILE & FOR LOOPS
If...else
a = 200
b = 100
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
b = 201
print("A") if a > b else print("=") if a == b else print("B is greater than A")
print("A is above 100")
if b > 300:
print("B is above 300!")
else:
print("B is not above 300!")
pass Having an empty if statement like this, would raise an error without the pass statement
While Loops
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
while i < 6:
i += 1
if i == 3:
continue
print(i)
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
print(x)
print(x)
if x == "banana":
break
if x == "banana":
break
print(x)
if x == "banana":
continue
print(x)
print(x)
print(x)
print(x)
print(x)
else:
print("Finally finished!")
if x == 3: break
print(x)
else:
print("Finally finished!")
pass
F...ELSE, WHILE & FOR LOOPS
If...else
a = 200
b = 100
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
a is greater than b
if a > b: print("a is greater than b")
a is greater than b
print("A") if a > b else print("B")
A
a = 200b = 201
print("A") if a > b else print("=") if a == b else print("B is greater than A")
B is greater than A
if a > 100:print("A is above 100")
if b > 300:
print("B is above 300!")
else:
print("B is not above 300!")
A is above 100
B is not above 300!
if a > b:B is not above 300!
pass Having an empty if statement like this, would raise an error without the pass statement
While Loops
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
1
2
3
i = 02
3
while i < 6:
i += 1
if i == 3:
continue
print(i)
1
2
4
5
6
i = 12
4
5
6
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
1
2
3
4
5
i is no longer less than 6
For Loops2
3
4
5
i is no longer less than 6
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
apple
banana
cherry
for x in "banana":banana
cherry
print(x)
b
a
n
a
n
a
for x in fruits:a
n
a
n
a
print(x)
if x == "banana":
break
apple
banana
for x in fruits:banana
if x == "banana":
break
print(x)
apple
for x in fruits:if x == "banana":
continue
print(x)
apple
cherry
for x in range(6):cherry
print(x)
0
1
2
3
4
5
for x in range(2, 6):1
2
3
4
5
print(x)
2
3
4
5
for x in range(2, 30, 3):3
4
5
print(x)
2
5
8
11
14
17
20
23
26
29
for x in range(6):5
8
11
14
17
20
23
26
29
print(x)
else:
print("Finally finished!")
0
1
2
3
4
5 Finally finished!
for x in range(6):1
2
3
4
5 Finally finished!
if x == 3: break
print(x)
else:
print("Finally finished!")
0
1
2
for x in [0, 1, 2]:1
2
pass
Comments
Post a Comment