DEV Community

nadirbasalamah
nadirbasalamah

Posted on

Python Tutorial - 2 Control Flow

Control flow is an essential part of programming. There are two types of control flow including branching and looping.

Comparison and Logical Operator

Comparation and logical operators are commonly used in the control flow mechanism. This is the list of comparison operators that can be used in Python. The comparison operator returns a boolean value.

Operator Description
== Equals to
!= Not equals to
> Greater than
>= Greater than or equals
< Less than
<= Less than or equals

This is an example of comparison operator usage in Python.

first = 5
second = 6

print(first > second)
print(first < second)
print(first != second)
Enter fullscreen mode Exit fullscreen mode

Output

False
True
True
Enter fullscreen mode Exit fullscreen mode

The and operator is an operator that returns true if the two conditions return true.

Condition Condition Result
False False False
False True False
True False False
True True True

The or operator is an operator that returns true if one or two conditions return true.

Condition Condition Result
False False False
False True True
True False True
True True True

This is an example of logical operator usage.

first = 6
second = 7

result_1 = first != 0 and first > second
result_2 = second > 5 or second == first

print(result_1)
print(result_2)
Enter fullscreen mode Exit fullscreen mode

Output

False
True
Enter fullscreen mode Exit fullscreen mode

Based on the code above, the and operator returns False because there is a condition that returns False which is first > second.
The or operator returns True because there is a condition that returns True which is second > 5.

and returns true if all conditions are true.

or returns true if one of the other conditions is true.

Branching in Python

Branching is a mechanism to execute a code based on a specific condition. There are many approaches to performing branching in Python.

Branching with if

This is the basic structure of branching with if.

if condition:
    code
Enter fullscreen mode Exit fullscreen mode

The code inside the if block is executed if the condition inside the if block is true.

This is an example of branching using if.

num = 24

if num % 2 == 0:
    print('even number')

Enter fullscreen mode Exit fullscreen mode

Output

even number
Enter fullscreen mode Exit fullscreen mode

Based on the code above, the code inside the if block is executed because the condition inside the if block is true.

Branching with if-else

This is the basic structure of branching with if-else.

if condition:
    code
else:
    other code
Enter fullscreen mode Exit fullscreen mode

The code inside the if block is executed if the condition inside the if block is true. Otherwise, the other code is executed inside the else block.

This is the example of branching with if-else.

num = 35

if num % 2 == 0:
    print('even number')
else:
    print('odd number')
Enter fullscreen mode Exit fullscreen mode

Output

odd number
Enter fullscreen mode Exit fullscreen mode

Based on the code above, the condition inside the if block is false then the code inside the else block is executed.

Branching with if-elif-else

This is the basic structure of branching with if-elif-else.

if condition:
    code
elif condition:
    code
else:
    code
Enter fullscreen mode Exit fullscreen mode

The if-elif-else is useful to perform branching with many conditions. This is an example of if-elif-else usage.

role = "Back-end"

if role == "Front-end":
    print("learn HTML, CSS and JS")
elif role == "Back-end":
    print("learn Java, Go and PHP")
else:
    print("learn any related topics")
Enter fullscreen mode Exit fullscreen mode

Output

learn Java, Go and PHP
Enter fullscreen mode Exit fullscreen mode

Based on the code above, the code is executed based on the role value.

Branching with match-case

The match-case branching works like the switch-case in other programming languages. This is the basic structure.

match value:
    case condition:
        code
    case condition:
        code
    case condition:
        code
    case _:
        default code
Enter fullscreen mode Exit fullscreen mode

This is the example of branching with match-case.

role = "Back-end"

match role:
    case "Front-end":
        print("learn HTML, CSS and JS")
    case "Back-end":
        print("learn Java, Go and PHP")
    case _: # default condition
        print("learn any related topics")
Enter fullscreen mode Exit fullscreen mode

Output

learn Java, Go and PHP
Enter fullscreen mode Exit fullscreen mode

Looping in Python

Looping is a mechanism to execute a code repeatedly. Looping is an essential tool for completing repetitive tasks like reading a record in a file, basic calculations, and so on. There are many approaches to performing looping in Python.

Looping with for

The for loop is suitable for executing repetitive tasks within an exact amount of time. For example, a certain task has to be completed 10 times. This is the basic structure of the for loop.

for value in iterables:
    code
Enter fullscreen mode Exit fullscreen mode

This is the sample code without using the for loop.

print(1)
print(2)
print(3)
print(4)
print(5)
Enter fullscreen mode Exit fullscreen mode

This is the modified code using the for loop.

for i in range(1,6):
    print(i)
Enter fullscreen mode Exit fullscreen mode

Output

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Based on the code above, the for loop code is executed with the range() function. The range() function returns a sequence of numbers based on the given start and end of the range. This is the basic structure of the range() function.

range(start,end,step)
Enter fullscreen mode Exit fullscreen mode
  • start defines the start of the sequence.
  • end defines the end of the sequence. The end value is not included in the sequence.
  • step defines the step value for generating the next sequences. By default, the step value is 1 which means each sequence value is incremented by 1.

The range(1,6) means generating a sequence of numbers from 1 up to but not including 6.

This is another example of a for loop with a custom range (range(2,11,2)) to display even numbers.

for i in range(2,11,2):
    print(i)
Enter fullscreen mode Exit fullscreen mode

Output

2
4
6
8
10
Enter fullscreen mode Exit fullscreen mode

Based on the code above, the even numbers from 2 up to but not including 11 are displayed. The range(2,11,2) generates sequence from 2 up to but not including 11 with the step value equals 2 which means each sequence value is incremented by 2.

Python range illustration

break and continue keyword

The break keyword stops the code execution. This keyword is usually used inside the loop. This is an example of break usage.

num = 10

while num != 0:
    if num % 4 == 0:
        print("done!")
        break # stops the execution
    print("stil running...")
    num -= 1 # decrement the value by 1
Enter fullscreen mode Exit fullscreen mode

Output

stil running...
stil running...
done!
Enter fullscreen mode Exit fullscreen mode

Based on the code above, the break keyword stops the execution if the condition is met.

The continue keyword continues the code execution into the next phase or skips to the next iteration. This is an example of continue keyword usage.

for i in range (1,7):
    if i == 5:
        print("skipped!")
        continue
    print(f"value: {i}")
Enter fullscreen mode Exit fullscreen mode

Output

value: 1
value: 2
value: 3
value: 4
skipped!
value: 6
Enter fullscreen mode Exit fullscreen mode

Based on the code above, the continue keyword skips to the next iteration if the condition is met.

Looping with while

The while loop is suitable for executing repetitive tasks within an uncertain amount of time. For example, a certain task has to be completed until a specific condition is met. This is the basic structure of the while loop.

while expression:
    code
Enter fullscreen mode Exit fullscreen mode

This is an example of while loop usage.

num = 1

while num <= 5:
    print(num)
    num += 1
Enter fullscreen mode Exit fullscreen mode

Output

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Based on the code above, the code inside the while loop is executed while the condition (in this case num <= 5) is true. If the condition is not met, then the loop is stopped. The += operator increments the num value by 1.

The num += 1 is equals to num = num + 1. The ++ and -- operator is not supported in Python.

When working with a loop, ensure the implementation and applied condition are correct to avoid an infinite loop.

Example 1 - Grade Checking

Let's create a Python program to check the grade based on the given score. For example, this table is used to check the grade based on the given score.

Score Grade
81-100 A
65-80 B
50-64 C
30-49 D
0-29 E

The solution is using branching. This is the complete example:

score = int(input("enter a score: "))

if score >= 81 and score <= 100:
    print("A")
elif score >= 65 and score <= 80:
    print("B")
elif score >= 50 and score <= 64:
    print("C")
elif score >= 30 and score <= 49:
    print("D")
elif score >= 0 and score <= 29:
    print("E")
else:
    print("invalid score")
Enter fullscreen mode Exit fullscreen mode

Output

Grade Checker Example with Python

Example 2 - Palindrome Checking

Let's create a program to check if the given word is a palindrome. Palindrome is a word that can be read equally forward and backward.

The naive solution is to compare the original word and the reversed word. If both of them are equal, then the given word is a palindrome. The naive solution walkthrough is illustrated in the picture below.

Check Palindrome with Naive Solution

This is the naive solution implementation using a while loop.

# get the word input from the user
word = input("insert a word: ")

# sanitize the input
word = word.lower()

# create a variable to store reversed word
reversed = ""
# create a variable to store the index
idx = len(word) - 1

# generate reversed word
while idx >= 0:
    reversed += word[idx]
    idx = idx - 1

# compare the original and reversed word
if word == reversed:
    print("palindrome")
else:
    print("not palindrome")
Enter fullscreen mode Exit fullscreen mode

Output

Palindrome Checker Example Valid

Palindrome Checker Example Invalid

Another approach is to create two indices for iterating through each character from forward and backward. If two characters from forward and backward are not equal, then the given word is not palindrome. The walkthrough of this approach is illustrated in the picture below.

Palindrome Checker with Two Pointers

Palindrome Checker with Two Pointers Invalid

This is the implementation of using two indices.

# get the word input from the user
word = input("insert a word: ")

# sanitize the input
word = word.lower()

# create two indices
front = 0 # forward tracking
back = len(word) - 1 # backward tracking

# store result
result = "palindrome"

# track each characters forward and backward
while front < len(word):
    if word[front] != word[back]:
        result = "not palindrome"
        break
    front += 1
    back -= 1

# display the check result
print(result)
Enter fullscreen mode Exit fullscreen mode

Output

Palindrome Checker Example Valid

Palindrome Checker Example Invalid

Sources

I hope this article helps you learn Python. If you have any feedback, please let me know in the comment section.

Top comments (0)