Date: Tuesday, September 12, 2023.
Due Date: Tuesday, September 19, 2023.
Goal: to use while loops in Python.
In this lab, we will be working on the while loop in Python.
Open the Python Idle and create a new file called lab4.py. Add your name and the lab number as a comment at the top.
Copy the following code discussed in the lecture, finding the minimum of a list of numbers, to the file lab4.py:
print("Enter n") n = int(input()) min = n while n != 0: if n < min: min = n print("Enter n") n = int(input()) print("The minimum of the list is", min)
Test the program to verify that it works.
Modify the program to find out the maximum of the list of numbers instead of the minimum. Change the name of the variable min to reflect the new functionality.
Like the last time, add the line
from random import *
at the beginning of the program, just below the comment.
Copy the new version of the following code discussed in class to the file lab4.py:
# program letting the user guess a secret number secretNumber = randint(1, 10) print("Try to guess a secret number between 1 and 10") guess = int(input()) while guess != secretNumber: print("No,", guess, "is incorrect.\n\n") print("Try again.") guess = int(input()) print("What a guesser! You are correct!")
Make the same modification you've made the last time, telling the player if their guess was higher or lower than the secret number. Test the program to make sure it works.
Modify the program so that after the player is done guessing, they can try another time, until they say that they don't. For this, we're going to place the code we got so far in another while loop.
Select the extire code for Ex. 2 a. and from the Format menu, select Indent Region. You can do this faster later by hitting Ctrl-]. Then before this region, on a new line, declare a variable
keepPlaying = "yes"
and right after that, add another while loop testing this variable, aligned all the way to the left:
while keepPlaying != "no":
Based on the alignment, the entire code we had before should now be the body of this new loop. At the end of the loop, aligned with the print statement, add another print statement asking the user if they want to play again, followed by "(yes/no)". Input the answer into the variable keepPlaying with no conversion.
At the end, closing the loop (aligned all the way to the left), add another print statement saying "Bye".
Upload the file lab4.py in Canvas, Assignments, Homework 4. You can wait until you finish the homework to upload both files at the same time.