This question already has an answer here:
Basically it's a guessing game and I have literally all the code except for the last part where it asks if the user wants to play again. how do I code that, I use a while loop correct?
heres my code:
import random
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
while guess == number:
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == yes:
guess= eval(input("Enter your guess between 1 and 1000 "))
if again == no:
break
separate your logic into functions
for example to get your integer input and for your main game
then you can play like
you can put it in a loop to run forever
I want to modify this program so that it can ask the user whether or not they want to input another number and if they answer 'no' the program terminates and vice versa. This is my code:
One big while loop around the whole program
Don't use
eval
(as @iCodex said) - it's risky, useint(x)
. A way to do this is to use functions:Using functions mean that you can reuse the same piece of code as many times as you want.
Here, you put the code for the guessing part in a function called
guessNumber()
, call the function, and at the end, ask the user to go again, if they want to, they go to the function again.