Python3 Ask the User if They Want to Play Again
Python Programming Fundamentals — Loops
Previously, we looked at the for loop and used it to print out a list of items for the user the select from. This is fantastic, however sometimes we want to practise something over and over until some condition is met.
Enter while. This loop structure allows you to continuously run some lawmaking until some condition is met (that you define). Let's starting time off by looking at what the while loop looks like in Python.
while <status>:
<stuff to practice>
This time, we'll create a number guessing game in which the computer will choice a random-ish number. I say random-ish considering most computers are only expert for pseudo-random numbers. This means, given plenty numbers it would be possible to predict the next number. For our purposes — and about purposes outside of Cryptography — this volition be expert plenty.
Permit's outset by creating a function called pickRandom() which volition be responsible for….you lot guessed it, picking the random number. It'south important when writing programs to choose role names that indicate what the function is responsible for.
def pickRandom():
rnd = x render rnd
I know what yous're thinking…that'southward non a random number. No, not yet atleast only we'll get to information technology trust me. Random number generation is just a bonus topic here, we're actually trying to understand the while loop.
Now that nosotros have this role, let'due south create our master() which will exist where the majority of our code will run from.
def main():
my_rnd = pickRandom()
usr_guess = input("Take a guess at my random number") while int(usr_guess) != my_rnd:
usr_guess = input("Sorry, effort over again: ") print("Wow, how did you know?")
Here we run into the while loop in action. First we call pickRandom() to generate our "random" number and follow that upward with a prompt for the user to try and guess that number. So we enter the while loop. The logic of this condition may be disruptive at commencement, we're checking to run into if the user'due south input is NOT equal to our random number. If this is evaluated to True (meaning the user guessed incorrectly) nosotros prompt the user to attempt again (and again, and again…). Now, if the user correctly guesses our number we print a congratulatory bulletin and the program ends. Let's see it in action:
*The important thing to detect here is that the while loop only executes when the condition evaluates to Truthful*
One of the prissy things about Python is that yous can use the else clause with your while, so instead of having the print outside of the loop you could include information technology with the loop similar and so:
def main():
my_rnd = pickRandom()
usr_guess = input("Take a guess at my random number") while int(usr_guess) != my_rnd:
usr_guess = input("Sorry, try again: ")
else:
print("Wow, how did you know?")
In this instance, information technology makes no difference except to await a little cleaner.
So now we have a basic number guessing game that could keep the boilerplate kid busy for maybe 2 minutes. But nosotros can practise better. Let's update our pickRandom() to get a new number each time the plan is ran:
def pickRandom(rnd_max):
from random import randint
rnd = randint(0,rnd_max) return rnd
Nosotros've added a few things hither so let'south go over them. The first thing we did was add a parameter to let some flexibility in how large the pool of numbers can be. Next we needed to pull in a office from another library. Libraries are collections of pre-written code that adds functionality to your programs when you lot include them. Here nosotros need the randint (read: Random Integer) office from the random library. If you wanted, yous could simply run
import random
to import ALL of the functions from the random library, just that's non necessary here. The randint function requires two arguments a and b which represent the lowest and highest numbers which can be generated. This is inclusive significant if you lot want random numbers between 0 and 100 yous can get 0 and up to and including 100 every bit possible numbers.
Another matter to note about the randint function is that information technology just returns whole numbers. No decimals here. If you're truly cruel and wish for your user to guess random numbers with decimals, you could utilise the random.random part which will generate a random decimal number between 0 and 1. And so for a number between 0 and 100 yous would type:
>>> rnd = random.random() * 100
>>> print(rnd)
48.47830553364575
Truly cruel indeed.
The just modification we demand to make to our master function is to add in the rnd_max argument.
def main():
my_rnd = pickRandom(twenty)
usr_guess = input("Take a guess at my random number: ") while int(usr_guess) != my_rnd:
usr_guess = input("Sorry, try again: ")
else:
impress("Wow, how did you lot know?!")
This will generate a random whole number between 0 and 20. Here's the whole thing so far:
def pickRandom(rnd_max):
from random import randint
rnd = randint(0,rnd_max) return rnd def main():
my_rnd = pickRandom(20)
usr_guess = input("Have a guess at my random number: ")while int(usr_guess) != my_rnd:
main()
usr_guess = input("Sorry, try again: ")
else:
print("Wow, how did you know?!")
This works well, but what if we wanted to play … multiple times? Allow's move our current principal function over to another office called play(). Other than the name change, the office will remain the same.
def play():
my_rnd = pickRandom(twenty)
usr_guess = input("Take a guess at my random number: ") while int(usr_guess) != my_rnd:
usr_guess = input("Sorry, try again: ")
else:
impress("Wow, how did y'all know?!")
Now let'southward update main to add a few things. One of these will be a flag variable which will determine whether the game is played multiple times. Allow'southward look at the lawmaking, and go over information technology slice past piece:
def principal():
again = True
while again:
play()
playAgain = input("Play once again? : ")
if playAgain[0].upper() == "N":
again = True
else:
again = False
Our flag variable is chosen again and we start it out as True. What would happen if nosotros started information technology out as False? Our while loop would never run, because it would evaluate our condition every bit False. Adjacent, we call play, which simply runs our game. Once the game is over the user will be prompted with a message asking if they would similar to play again. The side by side line looks a lilliputian strange:
if playAgain[0].upper() == "N":
This line basically says "If the first character of the contents of playAgain is the alphabetic character Due north". Since Python treats strings as lists of characters, you lot tin refer to each graphic symbol individually by using the same syntax yous would use on a list, namely the [x] syntax (where the 10 is whatsoever number between 0 and the length of your string). Next we accept that grapheme, and use a role from the string library chosen upper() which takes whatever graphic symbol and makes it capital letter. Finally nosotros check to come across if that character "is equal to" the letter "Northward".
It's of import to note the difference betwixt "=" and "==" when dealing with variables. "=" is an assignment, meaning variableName = value. "==" is a validation check, meaning "is variableName equal to value". Ever since I learned the deviation, in my head I always say "is equal to" when using "==".
If the user types "N", "n", "No","no", etc. and then the once more variable volition be prepare to Imitation, and the game volition end. If the user enters a response starting with anything other than the letter of the alphabet N then the game will continue with a new random number.
Hither's the concluding code with a wait at how the game runs:
def pickRandom(rnd_max):
from random import randint
rnd = randint(0,rnd_max) return rnd def play():
my_rnd = pickRandom(20)
usr_guess = input("Take a guess at my random number: ")while int(usr_guess) != my_rnd:
usr_guess = input("Sorry, try once more: ")
else:
impress("Wow, how did y'all know?!")def main():
main()
again = True
while again:
play()
playAgain = input("Play over again? : ")
if playAgain[0].upper() == "N":
again = Faux
That does it for this article, hopefully you learned a little chip about the while loop with some random numbers thrown in for fun. As an extension, you lot could exercise one of the following:
- Restrict the user to a certain number of turns.
- Accolade points to users and go along track of the highest scoring users in a variable.
- Add in a "college/lower" feature which aids the user in guessing the number (maybe later they exceed the max tries).
I promise you enjoyed this article, if and then please consider following me on Medium or supporting me on Patreon (https://www.patreon.com/TheCyberBasics). If you'd like to contribute but y'all're looking for a fiddling less commitment you can also BuyMeACoffee (https://www.buymeacoffee.com/TheCyberBasics).
In Manifestly English language
Show some dear past subscribing to our YouTube channel !
Source: https://python.plainenglish.io/programming-fundamentals-loops-2-0-b227c5fa4674
0 Response to "Python3 Ask the User if They Want to Play Again"
Postar um comentário