Fundamentals Flow

Module 1: Python Fundamentals

Review time!


Fundamentals: Flow Control in Python

Flow control refers to the way we can dictate the path or order in which our program’s instructions are executed. It allows us to make decisions, repeat actions, and create more dynamic and responsive code.

Comparison Operators

Before we delve into the various aspects of flow control, it’s essential to grasp the concept of comparison operators. Comparison operators are fundamental tools in programming and allow us to compare values, variables, or expressions.

Common comparison operators in Python are:

  • == (Double equals): Checks if two values are equal.
  • < (Less than): Checks if a value is less than another.
  • > (Greater than): Checks if a value is greater than another.
  • <= (Less than or equal to): Checks if a value is less than or equal to another.
  • >= (Greater than or equal to): Checks if a value is greater than or equal to another.
  • != (Not equal to): Checks if two values are not equal.

Understanding comparison operators is crucial because they form the foundation of decision-making in programming. By comparing values, we can create conditional statements (like if/else statements), that are the basis of flow control.

Let’s start by comparing two numeric values.

x = 3
y = 2

# Are x and y equal?
print(x == y)
# Are x and y different?
print(x != y)
# Is x higher than y?
print(x > y)

Comparison operators do not care whether the number is integer or float.

x = 3
y = 3.0

# Are x and y equal?
print(x == y)

However, they difference between numeric and string values.

x = 3
y = "3"

# Are x and y equal?
print(x == y)

We can compare strings too.

x = "hi"
y = "hello"

# Are x and y equal?
print(x == y)

Two strings will be considered equal only when they are an exact match. Lowercase and uppercase matter.

x = "hi"
y = "HI"

# Are x and y equal?
print(x == y)

When comparing strings, the > operator returns True if the first string is lexicographically larger than the second string.

x = "hello"
y = "hola"

# Is x higher than y?
print(x > y)

The if Statement

The if statement is one of the most fundamental aspects of flow control. It enables us to execute specific code blocks if a certain condition is met. In other words, it lets us make decisions in our code. Here’s a basic structure:

if <condition>:
    <code to run if the condition is True>

Pay special attention to the indentation of the code block inside the if condition.

<we always run this>

if <condition>:
    <code to run if the condition is True>

<we always run this>

For instance, let us write a code that turns any number lower than 5 into 5.

x = 2

# If x is lower than 5, turn it to 5
if x < 5:
  x = 5

print(x)
Exercise

Create a numeric variable, years. Write a code that prints “I am X years old” where X is the number in years, only if years is positive.

years = 5

if years > 0:
  print(f"I am {years} years old")
Exercise

Write a sentence containing the word “cat”, store it in a variable sentence. Create a code that replaces the word “cat” with the word “dog”, only if the word “love” also appears in sentence.

sentence = "I love cats"

if "cat" in sentence:
  sentence = sentence.replace("cat", "dog")

print(sentence)
Exercise

Fix the following codes.

# Prints the square root of a number only if its positive
x = 4

if x >= 0:
print(f"The square root of {x} is {x**0.5}")
# Replace a number by its power, if the original is even
x = 4

if x % 2 = 0
  x = x**2

print(x)
# Prints "Hello" if your name has more than 3 letters
name = "John"

if name > 3:
  print("Hello")

The else Statement

The else statement works in conjunction with if. It allows us to provide an alternative code block to execute if the if condition is not met. Here’s how it looks:

if <condition>:
    <code to run if the condition is True>
else:
    <code to run if the condition is False>

Once again, be very mindful of the indentation:

<we always run this>

if <condition>:
    <code to run if the condition is True>
else:
    <code to run if the condition is False>

<we always run this>
# This code checks if a student passed an exam
# Assuming a mark 0-10

grade = 7

if grade >= 5:
  print("You passed")
else:
  print("You have not passed")
Exercise

How would you write a function that checks if a number is even or odd?

x = 7

if x % 2 == 0:
  print("x is even")
else:
  print("x is odd")
Exercise

Read the following code cells. What will their output be?

name = "Alberto"

if "a" in name:
  print("The name contains the letter a")
else:
  print("The name does not contain the letter a")
x = 9

if x % 3 == 0:
  print("x is divisible by 3")
else
  print("x is not divisible by 3")
x = 5
y = 5 < 0

if y:
  print("x is negative")
else:
  print("x is positive")

We can include one if clause inside another.

x = 7

if x > 5:
  if x < 10:
    print("x is between 5 and 10")
  else:
    print("x is greater than 10")
else:
  print("x is lower than 5")
Exercise

Fix the following codes.

name = "Bella"

if name > 5:
  if len(name) = 1:
    print("Your name is just a letter?")
  else:
    print("The name is long")
else:
  print("The name is short")

The elif Statement

Sometimes, we need to check multiple conditions in a more complex decision-making process. That’s where the elif (short for “else if”) statement comes in. It allows us to evaluate additional conditions if the preceding ones are not met. Here’s how it’s used:

if <condition1>:
    <Code to execute if condition1 is True>
elif <condition2>:
    <Code to execute if condition2 is True>
else:
    <Code to execute if no conditions are True>

For instance, let’s determine if a number is positive, negative, or zero:

x = -5

if x > 0:
    print("x is positive")
elif x < 0:
    print("x is negative")
else:
    print("x is zero")

We can chain several elif clauses.

x = -10

if x > 10:
    print("x is greater than 10")
elif x > 0:
   print("x is positive")
elif x < -5:
  print("x is lower than -5")
elif x < 0:
    print("x is negative")
else:
    print("x is zero")

Pay special attention when chaining IF clauses. Sometimes when they are not properly ordered, some clauses will never happen.

Exercise

Which one of these clauses won’t happen, no matter x?

if x > 10:
  print("greater than 10")
elif x > 0:
  print("positive")
elif x < 0:
  print("negative")
elif x < -5:
  print("lower than -5")
else:
  print("zero")

Understanding these control structures allows us to create programs that can make decisions, adapt to different situations, and execute specific actions based on the conditions we define.


One-Line if Statements

It is customary to write if <condition> on one line and <code> indented on the following line, as we have seen above. But it is permissible to write an entire if statement on one line.

if <condition>: <code>

We can even separate several statements with semicolons.

if <condition>: <code1>;<code2>;<code3>
# This code turns negative numbers to 0
num = -3

if num < 0: num = 0

print(num)

In order to make the code easier to read, I do not recommend to write IF clauses in one line.

Conditional Expressions (Python’s Ternary Operator)

Python supports one additional decision-making entity called a conditional expression. It is also referred to as a conditional operator or ternary operator in various places in the Python documentation.

<expr1> if <condition> else <expr2>

<code1> is run if the <condition> is True, otherwise <expr2> will take place.

# This code converst a number to string
# If the number is below 100, it appears as float with 2 decimals.
# If the number is equal or above 100, it appears as integer.
num = 99
out = f"{num:.2f}" if num < 100 else f"{num:.0f}"

print(out)

When using small IF clauses to assign a variable, a conditional expression will often times be more readable.


Logical Operators

Logical operators are essential tools in Python for making complex decisions in our code. They allow us to combine multiple conditions and evaluate whether they are true or false as a group.

The and operator combines conditions, and all conditions must be True for the result to be True.

if <condition1> and <condition2>:
    <Code to execute if both condition1 and condition2 are True>
# This code decides if a students passes or not
# Based on their grade and attendance
grade = 8
attendance = 89

if (grade >= 5) and (attendance >= 80):
  print("You passed")
else:
  print("You have not passed")

The or operator combines conditions, and at least one condition must be True for the result to be True.

if <condition1> or <condition2>:
    <Code to execute if either condition1 or condition2 is True>
# This code decides if a students passes or not
# Based on their grade and attendance
grade = 8
attendance = 89

if (grade < 5) or (attendance < 80):
  print("You have not passed")
else:
  print("You passed")

The not operator negates a condition.

if not <condition>:
    <Code to execute if the condition is False>
# This code adds a dot at the end of a string
# if it does not have one

s = "Hello world"

if not s.endswith("."):
  s = s + "."

print(s)

We can combine logical operators to create complex conditions.


In the Next Session…

We will learn about loops.

They will help us automate repetitive tasks, iterate over data structures, and execute code efficiently based on certain conditions.

See you!