Python challenge: Controlling the flow
This post presents some basic commands for control flow, specifcally if
-statements, while
and for
-loops
If
-statements
Let’s start with a simple if statement:
if number > 0:
print("The number is larger than zero.")
Important to note here are two things: The if-clause ends with a colon and the body of the if-statement needs to be indented correctly.
An if-statement can be combined with an else
-clause in the following way:
if number > 0:
print("The number is larger than zero.")
else:
print("The number is not larger than zero.")
Again, the body belonging to the else branch needs to be indented.
The ternary operator is an alternative for if
..else
:
number = int(input("Please enter a number: "))
message="The number is larger than zero." if number > 0 else "The number is not larger than zero."
print(message)
.
Another variant is if
..elif
which allows to handle multiple branches in the flow of our code:
if number > 0:
print("You entered a positive number.")
elif number < 0:
print("You entered a negative number.")
else:
print("You entered zero.")
while
-loops
Following is a simple example of a while
-loop
userinput = ""
while userinput != "X":
print("Main menu")
print("---------")
print("Create - 1")
print("View all - 2")
print("Delete - 3")
print("Exit - X")
userinput = input("Enter your choice: ")
for
-loops
for
-loops can be used in various ways, e.g. for iterating through a string:
word = "hello"
for letter in word:
print(letter)
The limit of the loop can be defined using the range
keyword:
for i in range(10):
print(i, end=" ")
It is also possible to define the counting interval:
for i in range(0,10,2):
print(i, end=" ")
Last but not least, a for
-loop can be executed backwards:
for i in range(10,0,-1):
print(i, end=" ")