AI Basics with AK

Season 02 - Introduction to Python Programming

Arun Koundinya Parasa

Episode 07

IFs, FORs and WHILEs

Purpose of Loops?

  1. Execution Control
  2. Trigger a Reaction
  3. Respond to an event.

If has two parts:

  1. Control Statement
  2. What to Do and What not to do.

IFs

if True:
  print("This is always printed")
This is always printed
if False:
  print("This is never printed")
x = 2
if x == 2:
  print("x equals 2")
else:
  print("x does not equal 2")
x equals 2
if False:
  print("This is never printed")
else:
  print("This is always printed")
This is always printed
x = 2
if x == 2:
  print("x equals 2")
if x == 3:
  print("x equals 3")
else:
  print("x does not equal 2")
x equals 2
x does not equal 2
if x == 2:
  print("First block")
elif x == 3:
  print("Second block")
else:
  print("Third block")
First block
ControlBlock = 10
x = 4
if ControlBlock >= 10:
  if x == 2:
    print("First block")
  elif x == 3:
    print("Second block")
  else:
    print("Third block")
else:
  print("Fourth block")
Third block
ControlBlock = 8
if ControlBlock >= 10:
  if x == 2:
    print("First block")
  elif x == 3:
    print("Second block")
  else:
    print("Third block")
else:
  print("Fourth block")
Fourth block

FORs

for item in [0, 1, 2, 3, 4]:
  print(item)
0
1
2
3
4
print(list(range(5)))
[0, 1, 2, 3, 4]
for i in range(5):
  print("This is printed every time")
This is printed every time
This is printed every time
This is printed every time
This is printed every time
This is printed every time
for i in range(5):
  if i == 1:
    print(i)
  print("This is printed every time")
This is printed every time
1
This is printed every time
This is printed every time
This is printed every time
This is printed every time
for i in range(5):
  if i == 1:
    print(i)
    break
  print("This is printed every time")
This is printed every time
1

WHILEs

# Infinite Loop
#while True:
  #print("This is printed every time")
i = 0
while True:
  print("This is printed every time")
  i += 1
  if i == 2:
    break
This is printed every time
This is printed every time
# No Loop
while False:
  print("This is never printed")
i = 0
while i < 5:
  for j in range(i):
    print("This is printed every time",j,i)
  i += 1
This is printed every time 0 1
This is printed every time 0 2
This is printed every time 1 2
This is printed every time 0 3
This is printed every time 1 3
This is printed every time 2 3
This is printed every time 0 4
This is printed every time 1 4
This is printed every time 2 4
This is printed every time 3 4

Thank You

Open In Colab