While loops are helpful 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
syntaxwhile
statement includes a condition to test.A game stays active as long as the player has enough power.
Python
# The character's health starts at 10.
health = 5
# The character continues adventuring as long as their health is above 0.
while health > 0:
print(f"You are still adventuring, because your health is {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.")
count
set to 10.while
loop to print the current value of count
and then decrement the value of count
by 1.count
is greater than 0.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!
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:
unconfirmed_users
and prints a confirmation message for each.confirmed_users
.Python
# 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(f"Confirming user {current_user}...confirmed!")
# 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
We can use a while loop to run until a defined action is completed, such as emptying a list.
We should avoid a situation where we have an infinite loop.
1
1
1
1
1
Why does this output never stop?
The infinite loop is because there is no way for the test condition ever to fail.
current_number
is set to 1 and remains unchanged.count,
is introduced to track the number of times the loop has run.while
loop runs as long as the count
is less than 51
is printed, and the count is incremented by 1
after each iteration.You will unavoidably create an infinite loop at some point.
When you do, interrupt the process.
Infinite loops will not be a real problem until you use them in a program when some users run your program on their machines.
A function is a block of code that only runs when 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.
This is what a function looks like
To define functions, we need:
def
- the syntax necessary to initiate a functionmy_function
- the name of the function which has to describe well what it doesargument_one/two
- the arguments of the function which could change whenever we evaluate our functiondocstring
- the section marked with '''
, which explains and documents what our function doesreturn
- when the function executes the code, we should see a value as a result.Here is, for example, a function.
The function evaluates a statement and produces an output.
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
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
This is how we write this as a function called check_positive
This is how we write this as a function called check_positive
This is how we write this as a function called check_positive
This is how we write this as a function called check_positive
This is how we write this as a function called check_positive
This is how we write this as a function called check_positive
This is how we write this as a function called check_positive
What will the following return?
This is how we write this as a function called check_positive
What will the following return?
This is how we write this as a function called check_positive
What about the following?
This is how we write this as a function called check_positive
What about the following?
This is how we write this as a function called check_positive
What about the following?
This is how we write this as a function called check_positive
What about the following?
Let us now create a third condition: x=0
Let us now create a third condition: x==0
Let us now create a third condition: x==0
Let us now create a third condition: x==0
Let us now create a third condition: x==0
Here is another example of a function.
We create a function called add_five
with one parameter x
.
The function calculates and returns the sum of x
and 5
.
Here are the elements of the function:
def
)add_five
)x
)Here are the elements of the function:
x_plus_five = x + 5
)return x_plus_five
)The function add_five
, can be used to calculate the sum of various numbers and five.
The function add_five
, can be used to calculate the sum of various numbers and five.
Here is what happens if we use 77
as a parameter
We can, of course, assign the result of a function to an object.
We can write the same function in a different way
Objectives
Write a function that classifies a given number into one of three categories:
Let’s say the number is 3.
The output should look like the following:
Objectives
Write a function that classifies a given number into one of three categories:
Objectives
Write a function that classifies a given number into one of three categories:
Objective
Write a Python script that classifies a person into different age groups using a function based on the following criteria:
Let’s say the age is 15.
Instructions
Write a Python script that classifies a person into different age groups using a function based on the following criteria:
Instructions
Write a Python script that classifies a person into different age groups using a function based on the following criteria:
Objective
Write a Python script that classifies temperatures into different categories using a function based on the following criteria:
Use if-else statements within a function to classify the temperature into one of the categories.
Use if-else statements within a function to classify the temperature into one of the categories.
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 will be lost.
Thus, return
aims to return and preserve a value.
While loops enable repetitive execution until a specified condition is met, with careful handling needed to avoid infinite loops.
Functions enhance code reusability and organization, providing structure and scalability to programming tasks.
Combining loops and functions allows for efficient data manipulation and automation of repetitive tasks.
Thoughtful use of return
versus print
ensures clear outputs and preserves values for further computation.
Popescu (JCU): Lecture 6