Control Flows

Photo by David Clode on Unsplash

Control Flows

Introduction to Python #2

This article originally published on August 16th 2022

The code I wrote the article about so far ran from the top of the line to the bottom of the line. However, by utilizing conditionals or loops, programmers can make much more complex code.

Conditional Statements

1.if Statement

if statement runs the code block if the conditional statement is true.

if <CONDITIONS>:
      <CODE BLOCK>

Also, using multiple elifs and else statements, you can create more complex code flow. elif can be used as many as you want, but else statement can be used 0 or one times.

if <CONDITION>:
      <CODE BLOCK>
elif<CONDITION>:
      <CODE BLOCK>
else:
      <CODE BLOCK>

Example of if, elif and else

ifelifelse.png

# Python code
score = int(input("Enter the score: "))
if score > 80:
    print("Amazing !!")
elif score > 60:
    print("Just passed")
else:
    print("Failed")
# output
Enter the score: 59
Failed

Enter the score: 70
Just passed

Enter the score: 99
Amazing !!


2. match-case Statement

if, elif and else statement is useful, but if the number of the value you want to compare is one, match statement is another option. (similar to switch statement in C++, Java, JavaScript). Also, _ behaves like a wildcard and allow you to create default cases.

match <VALUE>:
      case <VALUE>:
            <CODE BLOCK>
      case <VALUE>:
            <CODE BLOCK>
      case <VALUE>:
            <CODE BLOCK>
      case _:
            <CODE BLOCK>

Example of match-case statement

import random

score = random.randint(1, 4) # generate the number 1 to 4.
match score:
        case 4:
            print("A")
        case 3:
            print("B")
        case 2:
            print("C")
        case 1:
            print("F")
        case _:
            print("Error")
# output
# first try
A
# second try
F
# third try
A

Loops

There are two types of loops in Python, which are for, and while like other programming languages. However, the way of writing code is slightly different.

1. while Statement

while loop repeats the process with specified conditions. Until the condition becomes True, while loop continues the processes.

while <CONDITION>:
      <CODE BLOCK>

Example of while loop

word = "Hello World"
while word:
    print(word),
    word = word[:-1]
# output
Hello World
Hello Worl
Hello Wor
Hello Wo
Hello W
Hello 
Hello
Hell
Hel
He
H


2. for Statement

Python for loop is different from other programming languages like C++. Python for loop repeats the process based on the iterable (sequence object).

 for <TARGET> in <ITERATABLE OBJECT>
         <CODE BLOCK>

Example of for loop

The code below prints the first four presidents of the United States using for loop.

for person in ['George Washington', 'John Adams', 'Thomas Jefferson', 'James Madison']:
    print(person)
#output
George Washington
John Adams
Thomas Jefferson
James Madison

Example of for loop with range()

range() function creates the iterable object, and by using range() function, for loop repeat the process specific time. The example below repeats printing numbers 0 to 4.

for x in range(5):
    print(x)
# output
0
1
2
3
4

Example with Dictionary

# dictionary type, storeing the subject name and its score
subjects = {'math': 84, 'science': 98, 'literature': 78, 'social science': 88, 'ethnic study': 67}

# average score
avg = 0

for subject in subjects:
    print(subject, subjects[subject], sep=": ")
    avg += subjects[subject]

avg /= len(subjects)

print("avg", avg, sep=": ")
# output
math: 84
science: 98
literature: 78
social science: 88
ethnic study: 67
avg: 83.0

break and continue

When the condition in a loop is alwaysTrue, the loop repeats the code block forever (also known as 'infinite loop'). Sometimes this happens as the programmer is unexpected. break statement breaks out from the infinite loop.

Example of break

The example code generates two random numbers, 0 to 6, and stores the values into variables one and two. If the two numbers are the same, show matching dice and stop the loop.

import random

while True:
    (one, two) = (random.randint(1, 6), random.randint(1, 6)) #create random two numbers 1 to 6
    print(one, two)
    if one == two:
        print("matching dice")
        break
# output
5 1
6 2
1 4
6 6
matching dice

Also, continue statement skips the lines after continue statement and returns to the beginning of the loop.

Example of continue

The example code below iterates 0 to 9, and if the variable num is odd, then skip and only show even numbers.

for num in range(10): # iterate 0 to 9
    if num % 2 == 1: continue
    print(num)
# output
0
2
4
6
8


Easy Mistake of Python Condition Statement

There are multiple statements like other programming languages, but unlike other programming languages, Python code do not need curly braces, but Python is really sensitive to indentation. This is because python was created to reduce the amount of code and programmers will be able to understand with ease. For example, the code below is valid.

x = 1;
y = 2;
if x > y:
    print(x);
print(y);
2

Process finished with exit code 0

Since x is 1 and y is 2, x > y is going to be false. Thus, the first print() statement, print(x) is skipped. This code is equivalent to the JavaScript code below:

if ( x > y ){
    console.log(x);
}
console.log(y);

If you want to output both x and y when x > y, then indentation is needed. Also, if you forget indentation after the conditional statement, a Syntax error occurs and exit with code 1.

x = 1;
y = 2;

if x > y :
print(x);
print(y);
  File "C:\Users\###\PycharmProjects\firstproject\app.py", line 4
    print(x);
    ^
IndentationError: expected an indented block after 'if' statement on line 3

Process finished with exit code 1

Summary

Python was created to simplify the code and make it hard for each programmer to create their own writing styles, which in turn for others can understand their code. I personally still have difficulty writing code since I learned Java, C++, and JavaScript first, which use '( )' and '{ }' instead ':' and indentation. However, once people get used to it, the code will be short and really easy to read.

Did you find this article valuable?

Support Kojiro Asano by becoming a sponsor. Any amount is appreciated!