Module 4 - Section 1 - While and Functions
Site: | ΕΛ/ΛΑΚ Moodle |
Course: | Python Lab |
Book: | Module 4 - Section 1 - While and Functions |
Printed by: | Guest user |
Date: | Thursday, 21 November 2024, 7:01 PM |
4.1.1 - While loop
A while loop is used when a program needs to loop until a particular condition occurs.
Oddly enough, a while loop can be used anywhere that a for loop is used. It can be used to loop until an increment variable reaches a certain value. So why we have a for loop if a while loop can do everything? The for loop is simpler to use and code. A for loop that looks like this:
for i in range(10):
print(i)
...can be done with a while loop that looks like this:
i = 0
while i < 10:
print(i)
i = i + 1
To achieve the same using a while loop we have to:
- Create a "sentinel" variable to count the number of times the loop has been executed
- Assign a starting value of zero to the above variable
- Create a condition and use it to get out of the loop when it becomes False
- Increase the "sentinel" variable
So a better use of the while loop is to ask for a reply from the user.
Copy the code to Thonny and save it as test_while (or whatever name you like) :
quit = "n"
while quit == "n":
quit = input("Do you want to quit? ")
What is the result of this code? If you reply n then the code stays in the loop and keeps asking. But if you reply anything else then the code gets out of the loop. It is not perfect but it is a start and you can try to make it better.
4.1.2 - Break
Another way to get out of a loop is to use the command break. So if we want a specific reply from a user then we can ask and if we get a wrong answer then we inform and ask again.
Copy the following code to Thonny and save it as test_while2.py (or whatever name you like) :
As an exercise create a code that asks the user to input his name and then his favorite color and then display a message "Hi name! Your favorite color is color! After that ask the player if he wants to play again and if he replies yes then ask again name and color if replies no exit and in any other case ask again.
Steps
- create a variable game and assign it True (when it turns to False game stops)
- create a while loop to check game variable
- input name and color to two variables
- create a variable cont to ask user if he want to continue
- with a while loop ask user if he wants to continue
You can view a sample solution here.
4.1.3 - The Guessing Game
Copy the following code to Thonny and save it as Guess.
We will play the game together and try to explain the steps using the Debug button. Input only integer numbers.
- Can you improve the program so in every attempt shows how many guesses you have left? Add the following lines after line 16. Don't forget the indentation.
guesses_left = 7 - guesses_taken
print("You have " + str(guesses_left) + " tries.")
- Can you cheat to win every time in the first guess?
- What happens if your guess is not integer?
4.1.4 - Functions
Don't Repeat Yourself (DRY)
Functions are used for two reasons. First, they make code easier to read and understand. Second, they allow code to be used more than once. You’re already familiar with the print() and input() functions. Python provides several builtin functions like these, but you can also write your own functions. A function is like a mini-program within a program. To better understand how functions work, let’s create one. Type this program into Thonny script editor and save it as hello_func.
def hello():
print("Hi!")
print("Hi!!!")
print("Hello World.")
Press the run button and then at the CLI area write
>>> hello()
>>> hello()
>>> hello()
By defining a function we can make the program easier to read. To define a function, start by using the def command. After the def command goes the function name. In this case we are calling it hello. We use the same rules for function names that we use for variable names.
Following the function name will be a set of parentheses and a colon. All the commands for the function will be indented inside. The code in the block that follows the def statement is the body of the function. This code is executed when the function is called, not when the function is first defined.
The hello() is a function call. In code, a function call is just the function’s name followed by parentheses, possibly with some number of arguments in between the parentheses. When the program execution reaches these calls, it will jump to the top line in the function and begin executing the code there. When it reaches the end of the function, the execution returns to the line that called the function and continues moving through the code as before.
In general, you always want to avoid duplicating code, because if you ever decide to update the code—if, for example, you find a bug you need to fix—you’ll have to remember to change the code everywhere you copied it.
As you get more programming experience, you’ll often find yourself deduplicating code, which means getting rid of duplicated or copy-and-pasted code. Deduplication makes your programs shorter, easier to read, and easier to update.
4.1.5 - Function Arguments
Functions can take parameters or arguments. These can be used to increase the flexibility of a function by altering what it does based on parameters passed to it. For example, write the following function to Thonny script editor and save it as printMyName.
def hello(name):
print("Hello " + name)
after that execute the code (press the play button) and inside the CLI area write :
>>> hello("Bob")
>>> hello("Alice")
The definition of the hello() function in this program has a parameter called name A parameter is a variable that an argument is stored in when a function is called. The first time the hello() function is called, it’s with the argument 'Bob'. The program execution enters the function, and the variable name is automatically set to 'Bob', which is what gets printed by the print() statement.
One special thing to note about parameters is that the value stored in a parameter is forgotten when the function returns. For example, if you added print(name) after hello('Alice') in the previous program, the program would give you a NameError because there is no variable named name. This variable was destroyed after the function call hello('Alice') had returned, so print(name) would refer to a name variable that does not exist.
This is similar to how a program’s variables are forgotten when the program terminates.
4.1.6 - Return from a Function
Return vs Print
Certain functions, such as int or str, return a value that can be used later. When a function returns a value the value is not printed in the output.
To return a value for your defined functions, you can use the return statement. The return statement cannot be used outside of a function definition.
Write the following code to Thonny script editor and save it as maxOfTwo:
The function takes two arguments and returns the maximum of two without printing anything.
Execute the code and in CLI write the following commands and observe the Variables area :
>>> print(max(3,9))
>>> z = max(11,2)
>>> print(z)
4.1.7 - More about functions
- Once you return a value from a function, it immediately stops being executed. Any code after the return statement will never be executed.
Copy the following code to Thonny script editor and save it as add3Numbers :
At the CLI area write
>>> print(addNumbers(4, 5, 19))
As you can see the function returns the value and the print command after the return does not execute.
- In programming, a docstring is a string literal specified in source code that is used, like a comment, to document a specific segment of code. Unlike conventional source code comments, docstrings are not stripped from the source tree when it is parsed, but are retained throughout the runtime of the program. This allows the programmer to inspect these comments at run time, for instance as an interactive help system.
The next function returns the quotient and the remainder of the Euclidian Division. Copy the script to Thonny script editor and save it as euclidianDivision.
Between the 2nd and the 7th line of the function there is the documentation of the function. As stated this documentation is not ignored by python. After execution of the script, we can test it.
>>> print(division(8,3))
>>> print(division(47,4))
The results is something like a list (called tuples) and we can print them separately the same way that we can print items of a list:
>>> print(division(47,4))[0] # The first item of the tuple, the quotient
>>> print(division(47,4))[1] # The second item of the tuple, the remainder
Also we can print the documentation of the function.
>>> print(division.__doc__)
This is extremely useful when we inspect someone else's scripts or we forgot what our code supposed to do!!
4.1.8 - Fortune teller
Copy the following function to Thonny script editor and save it as fortuneTeller :
Execute the code and at the CLI write :
>>> adviseMe ("Meet my friends tonight?")
The script contains two functions. The first getAnswer returns a value, string in this case, that can be used elsewhere. The second one adviseMe creates a random number between 1 and 9, pass this number to the first function and prints the value that is returned.
So the sequence is :
- We call the function adviseMe
- adviseMe creates a random number
- adviseMe is passing the random number as a parameter to function getAnswer
- getAnswer returns a value
- adviseMe prints the value that was returned from getAnswer
You can follow the sequence using the Debug button.
As an exercise download the fortuneTeller script from here and print the Docstrings of the two functions.