02. Control Flow - Conditional Blocks and Loops

Arindam BaidyaArindam Baidya
2 min read

Conditional statements

if

if condition :
    print("The condition is true!")
  • If the codintion after if keyword is true, the code block will get executed. Otherwise it will just ignored.
>>> age = int(input("How old are you? "))
How old are you? 22
>>> if age >= 18:
        print("You are adult!")
You are adult!

  • It is important to write a colon (:), and add an indentation - using tab or spaces.

if - else

if condition:
    print("The condition is true!")
else:
    print("The condition is false!")

elif

if condition:
    print("The condition is true!")
elif condition:
    print("Only the second condition is true!")
else:
    print("Both condition are false")

if under if

if age >= 18:
    if age == 18:
        print("You are exactly 18 years old")
    else:
        print("You are older than 18 years old")

Loops - while

while condition:

  • The while keyword allows us to execute code as long as a certain condition is true. This means that the code block can run repeatedly as long as the condition returns true.
>>> secret_number = 3
>>> guess = int(input("Guess a number between 5: "))
>>> while guess != secret_number:
        guess = int(intput("Guess a number between 5: "))
    else:
        print("Congratulations, you got it!")

Loops - for

for … in …:

>>> for i in range(10):
        print("i is: ", i)
>>> for i in range(2, 5)
        print(i)
  • The first argument in the range function is used to determine the initial value.
>>> for i in range(5):
        if(i == 2):
            break
        print(i)
>>> for i in range(5):
        if(i == 2)
            continue:
        print(i)
  • if/else Statements allow us to conditionally run code

  • A while loop makes it possible to repetitively execute code based on a certain condition

  • We can execute code for each item in a sequence with a for … in loop

References

Kodekloud

0
Subscribe to my newsletter

Read articles from Arindam Baidya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Arindam Baidya
Arindam Baidya