Would You Like to Play Again Pytho
Python Programming Fundamentals — Loops
Previously, we looked at the for loop and used information technology to print out a list of items for the user the select from. This is fantastic, notwithstanding sometimes we want to do 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). Allow's start off by looking at what the while loop looks like in Python.
while <condition>:
<stuff to exercise>
This fourth dimension, we'll create a number guessing game in which the computer volition option a random-ish number. I say random-ish because almost computers are but good for pseudo-random numbers. This means, given enough numbers it would be possible to predict the side by side number. For our purposes — and about purposes outside of Cryptography — this will be skillful enough.
Permit'due south start by creating a function called pickRandom() which volition exist responsible for….you lot guessed it, picking the random number. It'south important when writing programs to cull function names that signal what the function is responsible for.
def pickRandom():
rnd = 10 render rnd
I know what yous're thinking…that'due south not a random number. No, not withal atleast but we'll become to it trust me. Random number generation is merely a bonus topic here, we're really trying to empathise the while loop.
Now that we accept this function, let's create our main() which volition be where the majority of our code volition run from.
def master():
my_rnd = pickRandom()
usr_guess = input("Take a guess at my random number") while int(usr_guess) != my_rnd:
usr_guess = input("Sorry, endeavor again: ") print("Wow, how did you know?")
Hither we see the while loop in activity. Beginning we call pickRandom() to generate our "random" number and follow that up with a prompt for the user to endeavor and gauge that number. Then nosotros enter the while loop. The logic of this condition may exist confusing at offset, we're checking to meet if the user's input is NOT equal to our random number. If this is evaluated to True (pregnant the user guessed incorrectly) we prompt the user to try again (and again, and again…). Now, if the user correctly guesses our number we impress a congratulatory bulletin and the plan ends. Allow'southward see it in action:
*The important thing to notice here is that the while loop only executes when the condition evaluates to True*
One of the nice things about Python is that you can use the else clause with your while, and so instead of having the impress exterior of the loop you could include it with the loop like so:
def chief():
my_rnd = pickRandom()
usr_guess = input("Take a approximate at my random number") while int(usr_guess) != my_rnd:
usr_guess = input("Sad, try again: ")
else:
impress("Wow, how did you know?")
In this instance, it makes no difference except to wait a footling cleaner.
Then now nosotros have a bones number guessing game that could keep the average kid busy for perhaps 2 minutes. Merely we tin do amend. Let'south update our pickRandom() to become a new number each time the plan is ran:
def pickRandom(rnd_max):
from random import randint
rnd = randint(0,rnd_max) render rnd
We've added a few things hither and so let'due south go over them. The start thing nosotros did was add together a parameter to allow some flexibility in how large the puddle of numbers can be. Next we needed to pull in a part from another library. Libraries are collections of pre-written code that adds functionality to your programs when you include them. Here we need the randint (read: Random Integer) function from the random library. If yous wanted, you could simply run
import random to import ALL of the functions from the random library, but that'due south not necessary here. The randint part requires 2 arguments a and b which represent the lowest and highest numbers which tin exist generated. This is inclusive pregnant if you want random numbers between 0 and 100 you tin can get 0 and up to and including 100 as possible numbers.
Another thing to note about the randint function is that it only returns whole numbers. No decimals here. If y'all're truly cruel and wish for your user to estimate random numbers with decimals, you lot could use the random.random function which will generate a random decimal number between 0 and ane. And so for a number betwixt 0 and 100 you lot would type:
>>> rnd = random.random() * 100
>>> impress(rnd)
48.47830553364575 Truly cruel indeed.
The merely modification we need to make to our main part is to add together in the rnd_max statement.
def main():
my_rnd = pickRandom(20)
usr_guess = input("Take a guess at my random number: ") while int(usr_guess) != my_rnd:
usr_guess = input("Lamentable, try again: ")
else:
print("Wow, how did you know?!")
This volition generate a random whole number betwixt 0 and 20. Here'southward the whole thing then far:
def pickRandom(rnd_max):
from random import randint
rnd = randint(0,rnd_max) return rnd def primary():
my_rnd = pickRandom(20)
usr_guess = input("Take a guess at my random number: ")while int(usr_guess) != my_rnd:
main()
usr_guess = input("Sorry, try once more: ")
else:
print("Wow, how did you know?!")
This works well, but what if we wanted to play … multiple times? Let'south move our current chief role over to another function chosen play(). Other than the name change, the function will remain the aforementioned.
def play():
my_rnd = pickRandom(xx)
usr_guess = input("Take a guess at my random number: ") while int(usr_guess) != my_rnd:
usr_guess = input("Sorry, endeavor once more: ")
else:
print("Wow, how did you know?!")
Now let'south update primary to add together a few things. One of these volition be a flag variable which will make up one's mind whether the game is played multiple times. Let's look at the code, and get over it piece by piece:
def main():
once again = Truthful
while again:
play()
playAgain = input("Play again? : ")
if playAgain[0].upper() == "Due north":
once again = True
else:
again = Fake Our flag variable is called again and nosotros start it out as Truthful. What would happen if nosotros started it out equally Faux? Our while loop would never run, because it would evaluate our condition as False. Next, we telephone call play, which just runs our game. One time the game is over the user will exist prompted with a bulletin asking if they would similar to play again. The next line looks a niggling strange:
if playAgain[0].upper() == "N": This line basically says "If the showtime character of the contents of playAgain is the letter North". Since Python treats strings as lists of characters, y'all tin refer to each character individually by using the same syntax you would utilise on a list, namely the [ten] syntax (where the 10 is any number between 0 and the length of your cord). Side by side we take that graphic symbol, and apply a function from the string library called upper() which takes any graphic symbol and makes it capital letter. Finally nosotros check to see if that character "is equal to" the alphabetic character "N".
It'southward of import to annotation the difference between "=" and "==" when dealing with variables. "=" is an assignment, meaning variableName = value. "==" is a validation check, pregnant "is variableName equal to value". Ever since I learned the difference, in my caput I always say "is equal to" when using "==".
If the user types "N", "northward", "No","no", etc. then the again variable volition be set to False, and the game will terminate. If the user enters a response starting with anything other than the alphabetic character North then the game will continue with a new random number.
Hither's the concluding code with a look 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 approximate at my random number: ")while int(usr_guess) != my_rnd:
usr_guess = input("Distressing, try again: ")
else:
impress("Wow, how did you know?!")def principal():
main()
once again = True
while once more:
play()
playAgain = input("Play again? : ")
if playAgain[0].upper() == "Northward":
again = Imitation
That does it for this article, hopefully you learned a little bit most the while loop with some random numbers thrown in for fun. As an extension, you could do 1 of the following:
- Restrict the user to a certain number of turns.
- Accolade points to users and keep track of the highest scoring users in a variable.
- Add in a "higher/lower" feature which aids the user in guessing the number (maybe subsequently they exceed the max tries).
I promise you enjoyed this article, if so please consider post-obit me on Medium or supporting me on Patreon (https://world wide web.patreon.com/TheCyberBasics). If you'd like to contribute but you're looking for a lilliputian less delivery y'all can also BuyMeACoffee (https://www.buymeacoffee.com/TheCyberBasics).
In Plainly English
Show some dear by subscribing to our YouTube channel !
Source: https://python.plainenglish.io/programming-fundamentals-loops-2-0-b227c5fa4674
0 Response to "Would You Like to Play Again Pytho"
Post a Comment