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
syntaxwhile
statement includes a condition to test.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.")
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
.# 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
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.
1
1
1
1
1
Why does this output never stop?
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
is set to 1 and remains unchanged.count
is introduced to keep track of the number of times the loop has run.while
loop runs as long as count
is less than 51
is printed, and count is incremented by 1
after each iteration.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.
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.
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>
To define functions we need:
def
- the syntax necessary to initiate a functionmy_function
- 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 codition: x==0
Let us now create a third codition: x==0
Let us now create a third codition: x==0
Let us now create a third codition: x==0
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
.
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
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 an R script that classifies a given number into one of three categories using a function:
Let’s say the number is 3.
The output should look like below:
Objectives
Write an R script that classifies a given number into one of three categories using a function:
Objective
Write an R script that classifies a person into different age groups using a function, based on the following criteria:
Let’s say the age is is 15.
Instructions
Write an R script that classifies a person into different age groups using a function, based on the following criteria:
Objective
Write an R 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.
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
Popescu (JCU): Lecture 6