Skip to content

How to use if statement and loops in Python

How to use if, else if, else in Python

In Below code there are variables declared on top then using Operating System (os library imported on top) get the development environment from the system in current_env and then compare it with the variables declared and print.

import os

DEVELOPMENT = "development"
PRODUCTION = "production"
STAGING = "staging"
CODE_SPACE = "code_space"
LOCAL = "local"
current_env = os.environ.get("ENV_NAME", DEVELOPMENT)
if current_env == DEVELOPMENT:
    print("Development environment")
elif current_env == PRODUCTION:
    print("Production environment")
elif current_env == STAGING:
    print("Staging environment")
elif current_env in [CODE_SPACE, LOCAL]:
    print("Codespace or local environment")
    print("Unknown environment")

Development Environment

However, if we change the ENV_NAME variable then it should show “Unknown environment”. When changed to the ENV_NAME to code_space, this should look for either CODE_SPACE or LOCAL using the “in” operator?

$ export ENV_NAME="aaaa"

#OutputUnknown environment$ export ENV_NAME="code_space"

#Output Codespace or local environment

Useful loops in Python

Most useful loops in Python are:

While loop &

For-in loop

NAMES = ["John", "Paul", "George", "Ringo"]
AGES = [20, 21, 22, 23]
i = 0
while i < len(NAMES):
    print(NAMES[i], AGES[i])
    i += 1

John 20
Paul 21
George 22
Ringo 23

The while loop is clear to understand where it is looping until the length of the names. While has chances of running in infinite loop while in some complex logics. Therefore, it is safer to use For-in loop in Python as it is little bit less bug prone and more readable.

for name in NAMES:

Above is straight forward For-in loop where each name is picked from the collection of NAMES and then printed the names line by line.

How to Iterate through two collections at the same time in Python?

To iterate through two collections use of “zip” keyword clips the two collections together and builds a new list in memory. Then looping through name, age and finally interpolating the values while printing as a string.

for name, age in zip(NAMES, AGES):
    print(f"{name} {age}")
John 20
Paul 21
George 22
Ringo 23

How to print python collection in reverse?

Similarly, the term “reversed” can be used to reverse the collection.

for name in reversed(NAMES):

How to iterate through ranges in Python?

The term “range” can be used in Python to iterate through the ranges without loading up values in the memory.

for i in range(5):

The in the above iterations however it was not possible to find out which iteration is on at the time of printing. So, to identify the iteration there is a handy method called “enumerate” in Python.

for i in enumerate(NAMES):
	print(f"{i} {name}")

(0, 'John')
(1, 'Paul')
(2, 'George')
(3, 'Ringo')

One Comment

Leave a Reply

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