L6: While Loops and Functions

Bogdan G. Popescu

John Cabot University

While Loops

Introduction

While loops are useful because they let the code run until the user decides to quit the program.

Thus, they set up infinite loops until the user does something to end the loop.

A while loop tests an initial condition. If the condition is true, the loop starts executing.

Every time the loop finishes, the condition is reevaluated.

When the condition becomes false, the loop stops executing.

While Loops

while syntax

# Set an initial condition.
game_active = True

# Set up the while loop.
while game_active:
    print("The game is running.")
    # After some event, set game_active to False to stop the loop
    game_active = False

# Do anything else you want done after the loop runs.

While Loops

Syntax

  • A while loop needs an initial condition that starts out true.
  • The while statement includes a condition to test.
  • All of the code in the loop will run as long as the condition remains true (e.g., numeric comparisons, boolean values).
  • As soon as something in the loop changes the condition such that the test no longer passes, the loop stops executing.
  • Any code that is defined after the loop will run at this point.

While Loops

Example

A game stays active as long as the player has enough power

# The character's health starts out at 10.
health = 5

# The character continues adventuring as long as their health is above 0.
while health > 0:
    print("You are still adventuring, because your health is %d." % health)
    # Your adventure code would go here, which includes events that can decrease health.
    # We can simulate that by reducing the health by 1 each iteration.
    health -= 1

print("\nOh no, your health dropped to 0! You can no longer continue the adventure.")

While Loops

Exercise

  1. Objective: Create a countdown timer that counts down from a specified number to 0.
  2. Starting Point: You will start with a variable count set to 10.
  3. Task: Use a while loop to print the current value of count and then decrement the value of count by 1.
  4. Condition: The loop should continue running as long as count is greater than 0.
  5. End Message: When the loop ends, print “Time is Up!”

While Loops

Exercise

# Start the countdown from 10.
count = 10

# Continue the countdown as long as count is greater than 0.
while count > 0:
    print("Current count is %d." % count)
    # Decrease the count by 1.
    count -= 1

# Print the end message when the countdown reaches 0.
print("\nTime's up!")
Current count is 10.
Current count is 9.
Current count is 8.
Current count is 7.
Current count is 6.
Current count is 5.
Current count is 4.
Current count is 3.
Current count is 2.
Current count is 1.

Time's up!

While Loops

Using while loops to process items in a list

We can pop items out of a list.

We can use a while loop to pop items from a list one at a time.

Let us say we want to do the following:

  • Initialize lists of unconfirmed and confirmed users.
  • Iteratively pops users from unconfirmed_users and prints a confirmation message for each.
  • Appends each confirmed user to confirmed_users.
  • Prints the (now empty) list of unconfirmed users.
  • Prints the list of confirmed users.

While Loops

Using while loops to process items in a list

# Start with a list of unconfirmed users, and an empty list of confirmed users.
unconfirmed_users = ['Ada', 'Billy', 'Clarence', 'Daria']
confirmed_users = []

# Work through the list, and confirm each user.
while len(unconfirmed_users) > 0:
    
    # Get the latest unconfirmed user, and process them.
    current_user = unconfirmed_users.pop()
    print("Confirming user %s...confirmed!" % current_user)
    
    # Move the current user to the list of confirmed users.
    confirmed_users.append(current_user)

print("Confirmed users:")
for user in confirmed_users:
    print('- ' + user)
Confirming user Daria...confirmed!
Confirming user Clarence...confirmed!
Confirming user Billy...confirmed!
Confirming user Ada...confirmed!
Confirmed users:
- Daria
- Clarence
- Billy
- Ada

While Loops

Accidental infinite loops

We may want to use a while loop to run until a defined action is completed, such as emptying out a list

We should avoid a situation where we have an infinite loop.

current_number = 1

# Count up to 5, printing the number each time.
while current_number <= 5:
    print(current_number)
1
1
1
1
1

Why does this output never stop?

While Loops

Accidental infinite loops

The reason for the infinite loop is that there is no way for the test condition to ever fail.

The following is for example a way to fix the infinite loop:

current_number = 1

# Count up to 5, printing the number 1 each time.
count = 0
while count < 5:
    print(current_number)
    count += 1  # Increment the count
1
1
1
1
1

While Loops

Accidental infinite loops

current_number = 1

# Count up to 5, printing the number 1 each time.
count = 0
while count < 5:
    print(current_number)
    count += 1  # Increment the count
  • current_number is set to 1 and remains unchanged.
  • A new variable count is introduced to keep track of the number of times the loop has run.
  • The while loop runs as long as count is less than 5
  • Inside the loop, the number 1 is printed, and count is incremented by 1 after each iteration.

Some thoughts

You will create an infinite loop at some point unavoidably.

When you do, interrupt the process

Infinite loops will not be a real problem until you use them in a program whenre there are users who run your program on their machines.

Functions

Introduction

A function is a block of code which only runs when it is called.

You can pass input values or data, known as arguments, into a function.

The function performs some operations with the data used as input

The function should produce an output as a result.

Functions

Introduction

Functions

Introduction

Functions

Introduction

Functions

Introduction Functions

This is what a function looks like

def my_function(argument_one, argument_two):
    '''
    Do something interesting with my function.

    Inputs:
      argument_one: this is a very important value.
      argument_two: this is also an extremely important value

    Returns: something magical and mysterious
    '''
    <do magic here>
    <also write some>
    <statements>
    
    return <return_value>

Functions

Introduction

To define functions we need:

  • def - the syntax necessary to initiate a function
  • my_function - name of the function which has to describe well what it does
  • argument_one/two - the arguments of the function which could change whenever we evaluate our function
  • docstring - the section marked with ''' which explains and documents what our function does
  • return - when the function executes the code, we should see a value as a result.

Functions

Examples

Here is for example a function.

The function evaluates a statement and produces an output

Functions

Examples

Here is for example a function.

The function evaluates a statement and produces an output

This is what we had before using an if-else statement

Functions

Examples

Here is for example a function.

The function evaluates a statement and produces an output

This is what we had before using an if-else statement

x = -5
if x > 0:
  print('x is positive!')
else:
  print('x is negative or zero!')
x is negative or zero!

Functions

Examples

This is how we write this as a function called check_positive

Functions

Examples

This is how we write this as a function called check_positive

def check_positive(x):

Functions

Examples

This is how we write this as a function called check_positive

def check_positive(x):
    if x > 0:

Functions

Examples

This is how we write this as a function called check_positive

def check_positive(x):
    if x > 0:
        message = 'x is positive!'

Functions

Examples

This is how we write this as a function called check_positive

def check_positive(x):
    if x > 0:
        message = 'x is positive!'
    else:

Functions

Examples

This is how we write this as a function called check_positive

def check_positive(x):
    if x > 0:
        message = 'x is positive!'
    else:
        message = 'x is negative or zero!'
    return message

Functions

Examples

This is how we write this as a function called check_positive

def check_positive(x):
    if x > 0:
        message = 'x is positive!'
    else:
        message = 'x is negative or zero!'
    return message

What will the following return?

check_positive(3)

Functions

Examples

This is how we write this as a function called check_positive

def check_positive(x):
    if x > 0:
        message = 'x is positive!'
    else:
        message = 'x is negative or zero!'
    return message

What will the following return?

check_positive(3)
'x is positive!'

Functions

Examples

This is how we write this as a function called check_positive

def check_positive(x):
    if x > 0:
        message = 'x is positive!'
    else:
        message = 'x is negative or zero!'
    return message

What about the following?

check_positive(-3)

Functions

Examples

This is how we write this as a function called check_positive

def check_positive(x):
    if x > 0:
        message = 'x is positive!'
    else:
        message = 'x is negative or zero!'
    return message

What about the following?

check_positive(-3)
'x is negative or zero!'

Functions

Examples

This is how we write this as a function called check_positive

def check_positive(x):
    if x > 0:
        message = 'x is positive!'
    else:
        message = 'x is negative or zero!'
    return message

What about the following?

check_positive(0)

Functions

Examples

This is how we write this as a function called check_positive

def check_positive(x):
    if x > 0:
        message = 'x is positive!'
    else:
        message = 'x is negative or zero!'
    return message

What about the following?

check_positive(0)
'x is negative or zero!'

Functions

Examples

Let us now create a third condition: x=0

Functions

Examples

Let us now create a third codition: x==0

def check_positive(x):
    if x > 0:
        message = 'x is positive!'

Functions

Examples

Let us now create a third codition: x==0

def check_positive(x):
    if x > 0:
        message = 'x is positive!'
    if x == 0:
        message = 'x is zero!'

Functions

Examples

Let us now create a third codition: x==0

def check_positive(x):
    if x > 0:
        message = 'x is positive!'
    if x == 0:
        message = 'x is zero!'
    else:
        message = 'x is negative or zero!'
    return message

Functions

Examples

Let us now create a third codition: x==0

def check_positive(x):
    if x > 0:
        message = 'x is positive!'
    if x == 0:
        message = 'x is zero!'
    else:
        message = 'x is negative or zero!'
    return message
check_positive(0)
'x is zero!'

Functions

Why Use Functions?

  • Code Reuse: Write code once, use it multiple times.
  • Organization: Break down tasks into smaller, manageable pieces.
  • Reduce Redundancy: Avoid repeating the same code in multiple places.
  • Maintainability: Easier to update or debug code in one place.
  • Readability: Makes code cleaner and more understandable.
  • Scalability: Functions allow projects to grow without becoming unmanageable.

Functions

Examples

Here is another example of a function.

We create a function called add_five that has one parameter x.

The function calculates and returns the sum of x and 5.

def add_five(x):
    x_plus_five = x + 5
    return x_plus_five

Functions

Examples

def add_five(x):
    x_plus_five = x + 5
    return x_plus_five

Here are the elements of the function:

  • Defining the function ( def )
  • A function name ( add_five )
  • Parameter(s), inside parentheses and separated by commas ( x )

Functions

Examples

def add_five(x):
    x_plus_five = x + 5
    return x_plus_five

Here are the elements of the function:

  • Code (x_plus_five = x + 5)
  • Returned value ( return x_plus_five)

Functions

Examples

The function add_five, can be used to calculate the sum of various numbers and five

# Function definition
def add_five(x):
    x_plus_five = x + 5
    return x_plus_five

Here is what happens if we use 5 as a parameter

# Function call, with argument 5
add_five(5)
10

Here is what happens if we use 77 as a parameter

# Function call, with argument 77
add_five(77)
82

Functions

Examples

We can of course assign the result of a function to an object.

# Function call, with argument 77
x=add_five(77)
x
82

We can write the same function in a different way

# Original Function
def add_five(x):
    x_plus_five = x + 5
    return x_plus_five
# Version 2
def add_five(x):
  return x + 5

Functions

Exercises with Functions 1

Objectives
Write an R script that classifies a given number into one of three categories using a function:

  • Positive: If the number is greater than 0
  • Negative: If the number is less than 0
  • Zero: If the number is exactly 0

Let’s say the number is 3.

The output should look like below:

classify_number(3)
The number is Positive.

Functions

Exercises with Functions 1

Objectives
Write an R script that classifies a given number into one of three categories using a function:

  • Positive: If the number is greater than 0
  • Negative: If the number is less than 0
  • Zero: If the number is exactly 0
number = 3
def classify_number(number):
    if number > 0:
        category = "Positive"
    elif number < 0:
        category = "Negative"
    else:
        category = "Zero"

    print(f"The number is {category}.")
classify_number(3)
The number is Positive.

Functions

Exercises with Functions 2

Objective
Write an R script that classifies a person into different age groups using a function, based on the following criteria:

  • Child: 0 to 12 years old
  • Teenager: 13 to 19 years old
  • Adult: 20 to 59 years old
  • Senior: 60 years old and above

Let’s say the age is is 15.

Functions

Exercises with Functions 2

Instructions
Write an R script that classifies a person into different age groups using a function, based on the following criteria:

age = 15
def classify_age(age):
    if 0 <= age <= 12:
        age_group = "Child"
    elif 13 <= age <= 19:
        age_group = "Teenager"
    elif 20 <= age <= 59:
        age_group = "Adult"
    else:
        age_group = "Senior"
    
    return f"You are a {age_group}."
classify_age(age)
'You are a Teenager.'

Functions

Exercises with Functions 3

Objective
Write an R script that classifies temperatures into different categories using a function based on the following criteria:

  • Cold: Less than 50 degrees Fahrenheit
  • Moderate: 50 to 75 degrees Fahrenheit
  • Warm: 76 to 90 degrees Fahrenheit
  • Hot: More than 90 degrees Fahrenheit

Functions

Exercises with Functions 3

Use if-else statements within a function to classify the temperature into one of the categories.

temperature = 50
def classify_temperature(temperature):
    if temperature < 50:
        category = "Cold"
    elif 50 <= temperature <= 75:
        category = "Moderate"
    elif 75 < temperature <= 90:
        category = "Warm"
    else:
        category = "Hot"
    
    return f"The temperature is {category}."
classify_temperature(temperature)
'The temperature is Moderate.'

Functions

Functions notes

A common problem when we first start programming is mixing the concepts of print and return

print prints the value of a variable on the screen.

If this value is not saved somewhere, it would be lost.

Thus, return aims to return and preserve a value