Learn Python in 10 Days – Day 3

Welcome back to our 10-day Python series! On day 1, we set up our Python environment and wrote our first program. On day 2, we covered Python basics like variables, data types, and operators. Today, we’ll dive into one of the most crucial aspects of programming: Control Flow.

Day 3 of 10: Control Flow

Control flow allows us to make decisions, repeat actions, and control the direction in which our program executes. For instance, when crossing a street, if the traffic light is green, you walk; otherwise, you wait. Similarly, you might wear your shades as long as the sun is out. This decision-making and repetitive behavior are central to control flow.

Let’s explore how Python handles this. We will learn about conditional flow and loops.

Conditional Statements

Let’s assume that you are a developer designing the user interface (UI) of your smartphone. If your mobile battery is below 20%, you want to push a notification asking the user to plug it in. If it’s full, a notification to unplug it. Otherwise, no notification. How do you implement this? This is where conditional statements come in.
Conditional statements in Python enable programs to make decisions and execute different blocks of code based on whether certain conditions are True or False. The primary keywords used for conditional statements are ifelif (short for “else if”), and else. Let’s explore how we can implement progressively more complicated conditional flow.

Single Condition

Let’s say you want to design a very simple push notification style for the battery power example we discussed. You want to push a single notification when the power is at 20%. Use a simple ‘if’ statement to do this.

Python
battery = 20 # initialize the value

if battery == 20:
  print("Please, plug in your charger.")

# Rest of the code...

If the expression, battery == 20, returns True, our code pushes the notification. Do you remember from day 2 what type of operator ‘==’ is?

Double Condition

if is the simplest conditional statement. An else statement can be used in conjunction with a if statement to provide an alternative block of code to execute when the if condition evaluates to False. For example,

Python
battery = 40 # initialize the value

if battery < 20:
  print("Please, plug in your charger.")

else:
  print("No need to plug in the charger.")
elif Statement

The elif statement allows for checking multiple conditions sequentially. When the if condition is False, Python checks the elif conditions in order. And finally, the else statement. Example:

Python
battery = 100 # initialize the value

if battery < 20:
  print("Please, plug in your charger.")

elif battery == 100:
  print("Battery is full. Unplug your charger.")

else:
  print("No need to plug in the charger.")

The above code first checks if the battery level is less than 20. If True, it pushes the notification inside the if condition. If False, it then checks the elif condition. If the battery is at 100 (True), the user gets the second notification. If that is False as well, the notification inside the else condition is pushed. Try different values of ‘battery’ and make sure you understand which block of the code is executed.

But how does Python know which block falls under which statement? Look out for the following things when you are using else…if statements.

  • True or False expression: The expression immediately after the ‘if’ keyword and before the colon ‘:’ must evaluate to either True or False.
  • The indentation: Indentation is the whitespace (spaces or tabs) in front of a line of code. You must indent the block of code you want to execute under a specific condition. Otherwise, Python will consider it excluded.
  • ‘else’ has no expression: ‘else’ doesn’t require a conditional expression. It is the default part executed when all previous conditions are false.
  • Sequence: Each if…else block or if…elif…else block must have the statements one after another. Fix the following code to check your understanding.
Python
battery = 18 # initialize the value

if battery < 20:
  print("Please, plug in your charger.")
print("Outside 'if'") # remove this line to fix the error

elif battery == 100:
  print("Battery is full. Unplug your charger.")
print("Outside 'elif'") # remove this line to fix the error

else:
  print("No need to plug in the charger.")
print("Outside 'else'") # This is fine
elif ladder

A ladder of the elif statement also allows for checking multiple conditions sequentially. Remember the bonus challenge from day 2? Let’s solve it properly here.

Bonus Challenge: Assign grades
Write a program that takes a student’s score (0–100) as user input. Then assign a grade as follows:

  • Print ‘Grade: A’ if score >= 90
  • Print ‘Grade: B’ if score >= 75
  • Print ‘Grade: C’ if score >= 60
  • Print ‘Grade: D’ if score >= 40
  • Print ‘Grade: F’ otherwise

Solution: Using elif ladder

Python
score = float(input("Enter the score: ")) # user input

if score >= 90:
  print("Grade: A")
elif score >= 75:
  print("Grade: B")
elif score >= 60:
  print("Grade: C")
elif score >= 40:
  print("Grade: D")
else:
  print("Grade: F")
Nested else…if

ifelif, and else statements can be nested within each other to handle more intricate scenarios. Nested statements are used when there are multiple layers of conditions. Let’s understand this with the following problem.

A movie theater has assigned you to set up an automated ticket checking machine for an age-restricted movie. The machine scans the ticket and ID of each person. Then it shows on the small screen whether the person is allowed in the movie or not. A person is allowed to watch the movie if they have a ticket and are at least 14 years old. Let’s use nested else…if to implement this condition.

Python
age = 20
has_ticket = True # False if no ticket

if age >= 14:
    if has_ticket: # Nested if
        print("You can enter the movie.")
    else: # Nested else
        print("You need a ticket.")
else:
    print("You're too young to watch this movie.")

The above program first checks if a person is at least 14 years old. If yes, it goes to the second layer of condition-checking to determine if the person has a ticket or not. On the contrary, if the person is below 14, they are not allowed to the movie regardless of whether they have a ticket or not. Play around with this code further to make sure the logic makes sense to you. The rest of the code is self-explanatory. However, please let me know in the comments if you still find it difficult to understand. Would you do it differently?

Combining conditional statements

You can combine multiple conditions using logical operators like and, or, etc. Let’s try the code below:

Python
a = 18
b = 3
c = 21

if a > b and c > b:
  print("Both conditions are True")

if a > b or a > c:
  print("At least one of the conditions is True")


Change the values and see if the logic still makes sense.
Now, you can implement conditional statements in your programs to impose more control over different blocks of code. Let’s move on to loops.

Loops

As the name suggests, loops let you repeat actions just like doing daily routines. If you need to repeat a particular block of code, you can use loops. Python offers two primary types of loops: for loops and while loops. Let’s look at their use.

for loop

The for loop in Python is used for iterating over a sequence (like a list, string, or range of numbers). It’s one of the most common ways to repeat actions when you know how many times to loop or what sequence you’re looping through. So, use for loops when the number of iterations is known, or you’re looping through items. We’ll look at a few examples.

Example 1: Iterating over a list
Python
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)


This loop runs 3 times, once for each item in the list, and assigns each item to the variable fruit during each iteration. For example, fruit = “banana” for the second iteration.

Example 2: Iterating over a string
Python
for char in "Word":
    print(char)


Strings are also sequences. This loop prints each character in the word “Word” one by one. So, it iterates 4 times.

Example 3: Iterating over a range

The range ( start, stop, step ) function in Python generates a sequence of numbers. For example, range(1, 6, 2) generates the sequence 1, 3, 5. So, the range( ) function generates a sequence starting from start (1st argument) up to, but not including stop (2nd argument), with an increment or decrement of step (3rd argument). However, you can also use the range( ) function with a single argument. For example, range(6) generates the sequence 0, 1, 2, 3, 4, 5 with the default start = 0 and step = 1. You can also use only 2 arguments. For example, range(1, 6) generates the sequence 1, 2, 3, 4, 5 with the default step = 1.
It can be useful when you need to loop a specific number of times or through numeric values. For example,

Python
for i in range(1, 6):
    print(i)


Try to play with the arguments of range( ).

while loop

The while loop repeatedly executes a block of code as long as a specific condition is met. So, use while loops when repetition depends on a condition that changes dynamically. Let’s try the following example:

Python
count = 1
while count < 7:
    print(count)
    count += 1  # Increment the counter

Notice that this generates the same output as the for loop above. Take note of a couple of things here:

  • Initialization: You have to initialize the counter before starting the while loop, i.e., ‘count = 1’ here.
  • Increment/ Decrement: You must increment or decrement the counter (count += 1) inside the while loop. This eventually makes the condition false. Do you remember the compound assignment operator (‘+=’) from day 2?
Controlling Loops: break, continue, pass

Now, we’ll learn three statements to control the flow of loops. These are very powerful, which let you handle exceptional incidents in a loop.

break

The break statement lets you exit the loop prematurely. This comes in handy when you need to search for an item in a list and terminate the search when you find the element. In the following example, we are searching for the target = 5 in the Fibonacci series. The break statement is executed when the condition i == target is met and the loop is terminated entirely.

Python
fibonacci = [1, 1, 2, 3, 5, 8, 13, 21]
target = 5 # change the value to 6 on second attempt

for i in fibonacci:
    if i == target:
        print(f"Breaking the loop at {i}!")
        break
else:
    print(f"Target not found")


Change the ‘target’ value to play around. Notice that the ‘else’ statement is outside the for loop. Try to figure out what would have happened if we put it inside the for loop and let me know in the comments.

continue

The continue statement skips the current iteration and continues with the rest of the iteration. This is useful when you need to skip a specific instance, but execute other iterations. In the following example, we are skipping the whitespace.

Python
blog = "AI With Tanim"
for char in blog:
  if char == ' ': # skipping the whitespace
    continue
  
  print(char, end="-") # Prints the character and ends with a "-"

print("Loop ends now.")


Can you think of another use case for this?

pass

The pass statement is a placeholder in Python that lets you do nothing. For example, the following code throws an error.

Python
for i in range(1, 6):
    # you are not yet sure what to put here.


So, you can simply use the pass statement to avoid the error and keep it as a placeholder for future implementation.

Python
for i in range(1, 6):
    pass # you are not yet sure what to put here.

Let’s implement the behavior of the continue statement from above using pass.

Python
blog = "AI With Tanim"
for char in blog:
  if char == ' ': # skipping the whitespace
    pass
  else:  
    print(char, end="-")

print("Loop ends now.")


Can you identify the differences? What would happen if I didn’t use the ‘else’ statement?

We’re done with loops. Let’s test your knowledge on conditional statements and loops.

Challenge Time!

  1. Challenge 1: Odd Even
    Write a program that takes a number from the user. Then prints “Even” if the number is even. Otherwise, prints “Odd” if the number is odd.
  2. Challenge 2: Sequence
    Write a program using a for loop that prints the squares of numbers from 1 to 10. Now, modify the code to use a while loop instead.
  3. Bonus Challenge: Prime Number
    Write a program that takes a number from the user and checks if it’s a prime number or not.
    Hint: A prime number is a whole number greater than 1 that has only two factors: 1 and itself. For example, 3 is a prime number because it can only be divided evenly by 1 and 3.

Try to solve all the challenges by yourself. This will let you taste the real joy and excitement of coding. We’ll solve the bonus challenge in the next part. However, give it your best shot to solve it since you have all the knowledge to solve this problem by now. Happy coding!

Conclusion

You now understand how Python handles decisions and repetition using conditionals and loops. These building blocks allow you to write smarter, more dynamic code. Up next on day 4: We’ll dive into functions and how to write reusable blocks of code like a pro.
Stay tuned!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top