How to Make a Game Play Again in Python

Photo by twinsfisch on Unsplash

Previously, we looked at the for loop and used it to impress out a list of items for the user the select from. This is fantastic, notwithstanding sometimes we desire to do something over and over until some status is met.

Enter while. This loop structure allows you to continuously run some lawmaking until some condition is met (that you lot define). Allow's start off past looking at what the while loop looks like in Python.

                while <condition>:
<stuff to do>

This time, we'll create a number guessing game in which the computer will option a random-ish number. I say random-ish considering virtually computers are only practiced for pseudo-random numbers. This ways, given enough numbers information technology would be possible to predict the next number. For our purposes — and almost purposes outside of Cryptography — this volition be good enough.

Let's start by creating a function chosen pickRandom() which will be responsible for….yous guessed it, picking the random number. Information technology's of import when writing programs to cull function names that bespeak 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 even so atleast merely we'll get to information technology trust me. Random number generation is just a bonus topic hither, we're actually trying to understand the while loop.

Now that nosotros take this role, let'due south create our main() which volition be where the majority of our lawmaking will 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("Pitiful, endeavor again: ")
print("Wow, how did you know?")

Here we see 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 estimate that number. And then we enter the while loop. The logic of this status may be disruptive at outset, we're checking to see if the user'south input is Non equal to our random number. If this is evaluated to True (pregnant the user guessed incorrectly) we prompt the user to try over again (and again, and again…). Now, if the user correctly guesses our number we print a congratulatory message and the program ends. Let'due south see information technology in action:

Exceptional guessing skills

*The important affair to observe hither is that the while loop only executes when the condition evaluates to True*

1 of the nice things about Python is that you lot can use the else clause with your while, so instead of having the print outside of the loop y'all could include it with the loop like so:

                def primary():
my_rnd = pickRandom()
usr_guess = input("Accept a estimate at my random number")
while int(usr_guess) != my_rnd:
usr_guess = input("Distressing, attempt again: ")
else:
impress("Wow, how did you lot know?")

In this instance, it makes no difference except to look a little cleaner.

So now we accept a basic number guessing game that could keep the average kid busy for maybe 2 minutes. But we can practise ameliorate. Let'southward update our pickRandom() to get 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 permit's get over them. The first thing we did was add together a parameter to allow some flexibility in how big the pool of numbers tin can be. Next nosotros needed to pull in a function from some other 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 you wanted, you could simply run

                import random              

to import ALL of the functions from the random library, but that's not necessary here. The randint function requires two arguments a and b which stand for the lowest and highest numbers which can be generated. This is inclusive pregnant if yous desire random numbers betwixt 0 and 100 you can become 0 and up to and including 100 as possible numbers.

Another matter to note about the randint role is that information technology only returns whole numbers. No decimals here. If you're truly barbarous and wish for your user to judge random numbers with decimals, yous could use the random.random function which will generate a random decimal number between 0 and 1. And then for a number betwixt 0 and 100 you would type:

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

Truly savage indeed.

The just modification nosotros need to brand to our master function is to add in the rnd_max argument.

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

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

This will generate a random whole number between 0 and xx. Here's the whole affair 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("Accept a guess at my random number: ")

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

master()

That was a little harder..animate being-force for the win

This works well, but what if we wanted to play … multiple times? Let'southward motion our current main part over to another function called play(). Other than the proper noun change, the office will remain the same.

                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("Pitiful, try again: ")
else:
print("Wow, how did you know?!")

Now let's update principal to add together a few things. One of these volition be a flag variable which will determine whether the game is played multiple times. Let'south look at the code, and become over it slice past piece:

                def main():
once again = Truthful
while again:
play()
playAgain = input("Play once again? : ")
if playAgain[0].upper() == "Due north":
again = True
else:
again = Faux

Our flag variable is called again and we starting time it out as Truthful. What would happen if we started information technology out as False? Our while loop would never run, because it would evaluate our condition as False. Side by side, we call play, which simply runs our game. Once the game is over the user volition be prompted with a bulletin request if they would like to play again. The side by side line looks a petty strange:

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

This line basically says "If the outset character of the contents of playAgain is the letter N". Since Python treats strings as lists of characters, you can refer to each grapheme individually by using the aforementioned syntax you would apply on a list, namely the [10] syntax (where the x is any number between 0 and the length of your string). Side by side we accept that character, and use a role from the cord library chosen upper() which takes any character and makes information technology uppercase. Finally we bank check to meet if that character "is equal to" the letter "N".

Information technology'due south of import 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 ever say "is equal to" when using "==".

If the user types "North", "northward", "No","no", etc. then the again variable volition be set up to False, and the game will end. If the user enters a response starting with annihilation other than the letter of the alphabet N then the game will proceed with a new random number.

Hither'southward the final code with a await at how the game runs:

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

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

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

principal()

Full game, multiple tries

That does it for this article, hopefully yous learned a niggling bit virtually the while loop with some random numbers thrown in for fun. As an extension, you could do i of the post-obit:

  • Restrict the user to a sure number of turns.
  • Award points to users and keep track of the highest scoring users in a variable.
  • Add in a "college/lower" characteristic which aids the user in guessing the number (maybe later on they exceed the max tries).

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

In Plain English language

Evidence some love past subscribing to our YouTube channel !

privettecomn1972.blogspot.com

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

0 Response to "How to Make a Game Play Again in Python"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel