Guess The Number In Python. Option To Close Game
i'm new to Python and programming and i'm trying to make the 'Guess the number' game. I made it work but i want the add the option to close the game using the brake statement. I've
Solution 1:
few changes and all is good
import random
attempts = 0
secretNumber = random.randint(1,100)
whileTrue:
print("Guess a number between 1 and 100. You can exit game anytime by typing q ")
guess=input()
stop=str(guess)
if stop== 'q':
print("You quitted the game")
breakelifnot guess.isdigit():
print("Only numbers are allowed")
else:
guess = int(guess)
attempts = attempts + 1if guess >100or guess<=0:
attempts = attempts - 1print("Not allowed.Only numbers between 1 and 100 allowed! \n")
elif guess < secretNumber and guess >0:
print("Nope!Try a higher number! \n")
elif guess > secretNumber and guess <100:
print("Nope!Try a lower number \n")
if guess == secretNumber:
attempts = str(attempts)
print("Congratulations you found it after " + attempts + " attempts")
break
Solution 2:
Beneath what Nick A and timgeb mentioned in their comments, you could adapt a few things. As I suggest in the following script, you might want to have a look at try and except. Please find comments inside the script.
import random
attempts = 0
secretNumber = random.randint(1,100)
# you can prompt the user within input()
stop=input("Guess a number between 1 and 100. You can exit game anytime by typing quit ")
whileTrue:
if stop == "quit": # as the the output of input() is a string, you can compare it with a string without str()print("You quitted the game")
breaktry: # work with try and except to avoid problems whenever the user writes something else than 'quit' or an integer
guess = int(stop)
attempts += 1if guess >100or guess<=0:
attempts = attempts - 1print("Not allowed.Only numbers between 1 and 100 allowed! \n")
elif guess < secretNumber and guess >0:
print("Nope!Try a higher number! \n")
elif guess > secretNumber and guess <=100: # note that it's <=. Otherwise nothing happens when the users chose 100print("Nope!Try a lower number \n")
except: # if it's not possible to turn 'stop' into an integer we'd like to perform the following
stop = input("No valid input, please guess again ") # Don't stop the script, let the user guess againcontinue# don't stop, but leave the current iteration (don't execute the rest) and start again at the beginning of the loop if guess == secretNumber:
attempts = str(attempts)
print("Congratulations you found it after " + attempts + " attempts")
break
stop = input("Guess again ") # prompt for a new number every round of the loop
Post a Comment for "Guess The Number In Python. Option To Close Game"