Mathematics, Sciences, and Technologies

Python for Scientists 2-2: If, Else, Elif Statements

,

If Statements

Following the last tutorial, we often want to check whether some condition holds or not, and depending on that, do different actions. This is exactly what an if statement is for. It has the syntax of if <boolean expression>:, followed by a code block with an indent. When <boolean expression> evaluates to True, that code block will then be executed. Otherwise, if <boolean expression> gives False, then the code block will not be run. Either way, the subsequent normal lines beyond the indented if code block will resume. Now let’s take a simple example:

x = float(input("Give me a number:"))
if x > 0:
print("It is positive!") # Notice the indent!
print("Test ended.")

This snippet asks for a number input and checks if it is positive so that it prints a message, and always also gives another message signaling the end of the program. If we enter 12, then we will obtain

Give me a number:12
It is positive!
Test ended.

as x > 0 is True. Otherwise, if we enter something like -3, we will get

Give me a number:-3
Test ended.

without the It is positive! part.

Else Statements

A very obvious extension to ask for is to also run other selected lines when the condition in the if statement is False for an alternative scenario. This can be done by appending an else block that is also indented at the same level as the if block. This will capture all other cases than the if condition. Continuing from the example above, we may write

x = float(input("Give me a number:"))
if x > 0:
print("It is positive!")
else:
print("It may be negative or zero.") # Notice the indent here too!
print("Test ended.")

Entering 12 will give the same outcome as above, but this time entering -3 will lead to

Give me a number:-3
It may be negative or zero.
Test ended.

The flowchart of an if-else statement is illustrated below.

Elif Statements

The above if-else statements can only address a “dichotomy”. Sometimes, we want to test multiple conditions (\( \geq 3\)). Hence, we have the elif statements, which come after an initial if statement or other elif statements: they will only be carried out if those previous conditions return False. For example,

my_score = 84
friend1_score = 95
friend2_score = 77
friend3_score = 0
def check_grade(score):
if score >= 90:
return("A")
elif score >= 80:
return("B")
elif score >= 70:
return("C")
elif score >= 60:
return("D")
else:
return("F")
print(f"My grade is {check_grade(my_score)}.")
print(f"Friend1's grade is {check_grade(friend1_score)}.")
print(f"Friend2's grade is {check_grade(friend2_score)}.")
print(f"Friend3's grade is {check_grade(friend3_score)}.")

Here we have defined a function to accept a score and report the corresponding grade via a chained if-elif-else statement: First, we check if score \( \geq 90 \) and returns “A”. If not, then we go one step lower and check if score \( \geq 80 \) and returns “B”. We do similar things for “70/C” and “60/D”, and if all the if/elif conditions fail, then we invoke the “catch-all” else statement and give “F” for score \( < 60 \). The code snippet then results in

My grade is B.
Friend1's grade is A.
Friend2's grade is C.
Friend3's grade is F.

Notice that only one of the if/elif/else blocks will be executed, and they are mutually exclusive. So even when friend1_score = 95, only the first if block will be run and the other lower grades will not be issued even if the score fulfills the subsequent elif conditions.

The flowchart of an if-elif-else structure is demonstrated below.

Exercise

Consider the wind speed conversion exercise in this tutorial again, refine the function so that it can convert knots to either units of km/h and m/s appropriately (\( 1 \) knot is \( 0.514 \) m/s), and also reject invalid, unphysical input that is negative or above \( 200 \) knots. Hint: for the unit selection, add an extra argument that accepts a string (e.g. "m/s", "km/h") and use it in an if-elif-else structure. Nest this with an enclosing if-else statement that checks the range of the input beforehand.

Suggested Solution
def kts_convert(kts, unit="km/h"):
if kts > 200 or kts < 0:
return("Invalid Wind Speed!")
else:
if unit == "km/h":
kmh = kts * 1.852
return(kmh)
elif unit == "m/s":
ms = kts * 0.514
return(ms)
else:
return("Unknown Unit!")
print(f"50 kts is {kts_convert(50):.1f} km/h.")
print(f"120 kts is {kts_convert(120, unit="m/s"):.1f} m/s.")
print("Invalid Example:", kts_convert(-1))

The three test cases give

50 kts is 92.6 km/h.
120 kts is 61.7 m/s.
Invalid Example: Invalid Wind Speed!

Leave a Reply

I’m Benjamin

Welcome to my Mathematical World! Here you can find posts and tutorials related to applied topics like Linear Algebra, Calculus, Differential Equations, and Programming. Feel free to leave comments and suggestions!

Discover more from Benjamin's Maths World

Subscribe now to keep reading and get access to the full archive.

Continue reading