How to Code Play Again in Python

Photograph by twinsfisch on Unsplash

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, however sometimes we want to practice something over and over until some condition is met.

Enter while. This loop structure allows yous to continuously run some lawmaking until some status is met (that you lot define). Let'due south first off past looking at what the while loop looks like in Python.

                while <condition>:
<stuff to do>

This time, nosotros'll create a number guessing game in which the computer will choice a random-ish number. I say random-ish because most computers are only good for pseudo-random numbers. This means, given enough numbers it would exist possible to predict the next number. For our purposes — and most purposes outside of Cryptography — this will be proficient enough.

Let's get-go by creating a function called pickRandom() which will exist responsible for….you guessed it, picking the random number. Information technology'southward of import when writing programs to choose part names that bespeak what the part is responsible for.

                def pickRandom():
rnd = 10

render rnd

I know what you're thinking…that's not a random number. No, not however atleast but we'll get to it trust me. Random number generation is just a bonus topic hither, we're really trying to understand the while loop.

Now that we take this role, allow'due south create our main() which volition be where the bulk of our code will run from.

                def main():
my_rnd = pickRandom()
usr_guess = input("Accept a estimate at my random number")
while int(usr_guess) != my_rnd:
usr_guess = input("Sorry, attempt once more: ")
print("Wow, how did you know?")

Here we see the while loop in activity. First we call pickRandom() to generate our "random" number and follow that up with a prompt for the user to attempt and guess that number. Then nosotros enter the while loop. The logic of this condition may exist confusing at first, we're checking to run across if the user'south input is NOT equal to our random number. If this is evaluated to True (meaning the user guessed incorrectly) we prompt the user to try again (and once more, and again…). Now, if the user correctly guesses our number we print a congratulatory message and the programme ends. Allow's see information technology in action:

Exceptional guessing skills

*The of import thing to observe here is that the while loop only executes when the condition evaluates to True*

One of the squeamish things about Python is that you can use the else clause with your while, so instead of having the impress outside of the loop you could include it with the loop similar so:

                def master():
my_rnd = pickRandom()
usr_guess = input("Have a guess at my random number")
while int(usr_guess) != my_rnd:
usr_guess = input("Sorry, endeavor once again: ")
else:
impress("Wow, how did you lot know?")

In this example, it makes no deviation except to look a picayune cleaner.

Then at present nosotros accept a basic number guessing game that could keep the average kid busy for maybe 2 minutes. But nosotros can do better. Permit's update our pickRandom() to get a new number each fourth dimension 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 here so permit's go over them. The first matter nosotros did was add together a parameter to allow some flexibility in how big the pool of numbers tin be. Next we needed to pull in a function 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, just that's non necessary here. The randint function requires 2 arguments a and b which correspond the everyman and highest numbers which tin can be generated. This is inclusive meaning if you want random numbers between 0 and 100 y'all can get 0 and up to and including 100 as possible numbers.

Another affair to note about the randint function is that it only returns whole numbers. No decimals here. If you lot're truly cruel and wish for your user to guess random numbers with decimals, you could use the random.random role which will generate a random decimal number between 0 and i. Then for a number between 0 and 100 you would type:

                >>> rnd = random.random() * 100
>>> print(rnd)
48.47830553364575

Truly barbarous indeed.

The just modification we need to brand to our main function is to add together in the rnd_max statement.

                def main():
my_rnd = pickRandom(20)
usr_guess = input("Have a estimate at my random number: ")

while int(usr_guess) != my_rnd:
usr_guess = input("Sorry, attempt once again: ")
else:
print("Wow, how did you know?!")

This will generate a random whole number between 0 and 20. Hither'southward the whole thing and so far:

                def pickRandom(rnd_max):
from random import randint
rnd = randint(0,rnd_max)
render rnd def principal():
my_rnd = pickRandom(20)
usr_guess = input("Take a guess at my random number: ")

while int(usr_guess) != my_rnd:
usr_guess = input("Sorry, effort again: ")
else:
print("Wow, how did you lot know?!")

main()

That was a little harder..brute-force for the win

This works well, but what if we wanted to play … multiple times? Let's move our current main role over to another role chosen play(). Other than the name change, the function will remain the same.

                def play():
my_rnd = pickRandom(20)
usr_guess = input("Have a gauge at my random number: ")

while int(usr_guess) != my_rnd:
usr_guess = input("Pitiful, try again: ")
else:
print("Wow, how did you know?!")

At present let's update main to add a few things. 1 of these will be a flag variable which volition determine whether the game is played multiple times. Let'due south wait at the code, and go over it piece past piece:

                def master():
once again = True
while over again:
play()
playAgain = input("Play again? : ")
if playAgain[0].upper() == "N":
over again = True
else:
again = False

Our flag variable is called again and we showtime it out as True. What would happen if we started it out as False? Our while loop would never run, because information technology would evaluate our condition as False. Next, we call play, which but runs our game. Once the game is over the user volition be prompted with a message request if they would like to play again. The side by side line looks a little foreign:

                if playAgain[0].upper() == "N":              

This line basically says "If the commencement character of the contents of playAgain is the letter of the alphabet N". Since Python treats strings as lists of characters, you can refer to each character individually by using the same syntax y'all would utilize on a list, namely the [ten] syntax (where the x is any number between 0 and the length of your string). Side by side we take that graphic symbol, and use a office from the string library called upper() which takes whatever character and makes it upper-case letter. Finally we cheque to encounter if that character "is equal to" the letter "N".

Information technology'southward important to note the difference between "=" 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 difference, in my head I always say "is equal to" when using "==".

If the user types "North", "n", "No","no", etc. and so the again variable volition exist prepare to False, and the game will end. If the user enters a response starting with anything other than the alphabetic character Due north so the game will continue with a new random number.

Here'due south the terminal code with a expect 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 again: ")
else:
print("Wow, how did y'all know?!")

def primary():
again = True
while again:
play()
playAgain = input("Play again? : ")
if playAgain[0].upper() == "N":
again = False

main()

Full game, multiple tries

That does it for this article, hopefully you learned a little scrap about the while loop with some random numbers thrown in for fun. As an extension, you could do one of the post-obit:

  • Restrict the user to a sure number of turns.
  • Award points to users and continue rails of the highest scoring users in a variable.
  • Add in a "higher/lower" characteristic which aids the user in guessing the number (maybe after they exceed the max tries).

I hope you enjoyed this article, if so please consider following me on Medium or supporting me on Patreon (https://world wide web.patreon.com/TheCyberBasics). If you lot'd like to contribute but you're looking for a little less commitment you can too BuyMeACoffee (https://www.buymeacoffee.com/TheCyberBasics).

In Plain English

Show some love by subscribing to our YouTube channel !

weaverwhileme.blogspot.com

Source: https://python.plainenglish.io/programming-fundamentals-loops-2-0-b227c5fa4674

0 Response to "How to Code Play Again in Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel