Play Again In a While Loop Python

Photo by twinsfisch on Unsplash

Previously, we looked at the for loop and used it to print out a listing of items for the user the select from. This is fantastic, even so sometimes we want to exercise something over and over until some condition is met.

Enter while. This loop structure allows you to continuously run some code until some condition is met (that you define). Let's start off by looking at what the while loop looks similar in Python.

                while <condition>:
<stuff to do>

This time, we'll create a number guessing game in which the computer volition option a random-ish number. I say random-ish considering most computers are only skillful for pseudo-random numbers. This ways, given plenty numbers information technology would be possible to predict the side by side number. For our purposes — and most purposes exterior of Cryptography — this will be skilful enough.

Permit'south start by creating a function chosen pickRandom() which volition be responsible for….you guessed it, picking the random number. It's important when writing programs to choose part names that indicate what the part is responsible for.

                def pickRandom():
rnd = ten

render rnd

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

Now that we accept this function, let'south create our main() which will be where the majority of our lawmaking volition run from.

                def chief():
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: ")
print("Wow, how did y'all know?")

Here we see the while loop in action. First we call pickRandom() to generate our "random" number and follow that up with a prompt for the user to try and estimate that number. Then we enter the while loop. The logic of this condition may be confusing at starting time, we're checking to see if the user's 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 over again, and once again…). Now, if the user correctly guesses our number we print a congratulatory message and the program ends. Let's see information technology in action:

Infrequent guessing skills

*The important matter to notice here is that the while loop simply executes when the condition evaluates to Truthful*

One of the dainty things virtually Python is that you tin can employ the else clause with your while, so instead of having the impress exterior of the loop y'all could include it with the loop similar so:

                def primary():
my_rnd = pickRandom()
usr_guess = input("Take a judge at my random number")
while int(usr_guess) != my_rnd:
usr_guess = input("Distressing, effort again: ")
else:
print("Wow, how did you lot know?")

In this instance, information technology makes no difference except to look a niggling cleaner.

So at present we accept a basic number guessing game that could proceed the boilerplate kid busy for maybe 2 minutes. But we can practise better. Allow's update our pickRandom() to go a new number each time the program is ran:

                def pickRandom(rnd_max):
from random import randint
rnd = randint(0,rnd_max)
return rnd

We've added a few things hither so let's get over them. The first thing we did was add a parameter to permit some flexibility in how big the pool of numbers tin can be. Next we needed to pull in a role from another library. Libraries are collections of pre-written code that adds functionality to your programs when y'all include them. Here we need the randint (read: Random Integer) function from the random library. If you wanted, yous could simply run

                import random              

to import ALL of the functions from the random library, but that's non necessary hither. The randint part requires two arguments a and b which represent the everyman and highest numbers which can be generated. This is inclusive meaning if you want random numbers betwixt 0 and 100 you can go 0 and up to and including 100 equally possible numbers.

Another thing to notation about the randint office is that it simply returns whole numbers. No decimals here. If you lot're truly barbarous and wish for your user to guess random numbers with decimals, y'all could use the random.random function which will generate a random decimal number between 0 and 1. And so for a number between 0 and 100 you would type:

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

Truly cruel indeed.

The only modification we need to make to our main function is to add in the rnd_max statement.

                def primary():
my_rnd = pickRandom(xx)
usr_guess = input("Accept a judge at my random number: ")

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

This will generate a random whole number between 0 and 20. Here'due south the whole thing and so far:

                def pickRandom(rnd_max):
from random import randint
rnd = randint(0,rnd_max)
return rnd def main():
my_rnd = pickRandom(twenty)
usr_guess = input("Take a gauge at my random number: ")

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

chief()

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

This works well, but what if nosotros wanted to play … multiple times? Let's movement our current chief function over to some other part called play(). Other than the name change, the function volition remain the aforementioned.

                def play():
my_rnd = pickRandom(xx)
usr_guess = input("Take a judge at my random number: ")

while int(usr_guess) != my_rnd:
usr_guess = input("Distressing, try once more: ")
else:
impress("Wow, how did you know?!")

Now let's update main to add a few things. One of these will exist a flag variable which will determine whether the game is played multiple times. Let'south look at the lawmaking, and go over it piece by piece:

                def chief():
over again = True
while over 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 we start information technology out as Truthful. What would happen if nosotros started information technology out as False? Our while loop would never run, considering it would evaluate our condition every bit False. Next, nosotros call play, which simply runs our game. Once the game is over the user will be prompted with a message asking if they would like to play again. The adjacent line looks a niggling strange:

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

This line basically says "If the offset character of the contents of playAgain is the letter N". Since Python treats strings equally lists of characters, you tin can refer to each character individually by using the same syntax you lot would use on a list, namely the [x] syntax (where the x is whatever number between 0 and the length of your string). Side by side we have that character, and employ a role from the string library called upper() which takes whatever graphic symbol and makes it uppercase. Finally we check to see if that grapheme "is equal to" the letter "Northward".

It's important to annotation the difference between "=" and "==" when dealing with variables. "=" is an assignment, meaning variableName = value. "==" is a validation cheque, meaning "is variableName equal to value". Ever since I learned the difference, in my head I ever say "is equal to" when using "==".

If the user types "N", "n", "No","no", etc. then the again variable will be set to Fake, and the game will stop. If the user enters a response starting with annihilation other than the letter N then the game volition continue with a new random number.

Here'south the final 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 again: ")
else:
impress("Wow, how did you know?!")

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

main()

Full game, multiple tries

That does information technology for this article, hopefully y'all learned a little bit nearly the while loop with some random numbers thrown in for fun. Equally an extension, you could exercise one of the post-obit:

  • Restrict the user to a certain number of turns.
  • Honor points to users and keep track 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 yous enjoyed this commodity, if so please consider following me on Medium or supporting me on Patreon (https://world wide web.patreon.com/TheCyberBasics). If you'd similar to contribute but you lot're looking for a footling less commitment yous can likewise BuyMeACoffee (https://world wide web.buymeacoffee.com/TheCyberBasics).

In Plain English

Prove some dear by subscribing to our YouTube aqueduct !

millerbuttenot.blogspot.com

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

0 Response to "Play Again In a While Loop Python"

Enviar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel