I have this very simple console game and I would like to restart the loop after the user answers a question but something doesn't seem to work properly.
import random
random_number = random.randrange(0, 500)
chosen_number = int(input("Please pick a number: "))
gameOn = 1
while gameOn == 1:
if chosen_number == 500 or chosen_number <= 0 :
print("Number must be below 500 and above 0.")
print(random_number)
chosen_number = int(input("Please pick a number: "))
continue
if chosen_number > random_number:
print("Too high")
chosen_number = int(input("Please pick a number: "))
elif chosen_number < random_number:
print("Too low")
chosen_number = int(input("Please pick a number: "))
else:
print("Congratulations, you guessed right. The number was " + str(chosen_number) + ".")
break
answer = input("Do you want to play again? Y/N ")
if answer == "Y" or "y" or "yes":
gameOn = 0
else:
print("Goodbye!")
You can do a simple thing, just put the whole code in a function and when you want to restart just call the function
Look at the code below:
import random
def game():
random_number = random.randrange(0, 500)
chosen_number = int(input("Please pick a number: "))
while True:
if chosen_number == 500 or chosen_number <= 0 :
print("Number must be below 500 and above 0.")
print(random_number)
chosen_number = int(input("Please pick a number: "))
continue
if chosen_number > random_number:
print("Too high")
chosen_number = int(input("Please pick a number: "))
elif chosen_number < random_number:
print("Too low")
chosen_number = int(input("Please pick a number: "))
else:
print("Congratulations, you guessed right. The number was " + str(chosen_number) + ".")
break
answer = input("Do you want to play again? Y/N ")
if answer.lower() == "y" or "yes": # Lower() is used for changing the whole string to lowercase
game()
else:
print("Goodbye!")
When you ask to play again you are setting gameOn to be 0 (as gameOn needs to be 1), which will exit the loop, your code should look like this
if answer in ("Y", "y", "yes"):
print("Starting again")
else:
print("Goodbye!")
gameOn = 0
for further clarification since you are choosing a number each game you need to put that into the loop as well
import random
gameOn = 1
while gameOn == 1:
random_number = random.randrange(0, 500)
chosen_number = int(input("Please pick a number: "))
if chosen_number == 500 or chosen_number <= 0 :
print("Number must be below 500 and above 0.")
print(random_number)
chosen_number = int(input("Please pick a number: "))
continue
if chosen_number > random_number:
print("Too high")
chosen_number = int(input("Please pick a number: "))
elif chosen_number < random_number:
print("Too low")
chosen_number = int(input("Please pick a number: "))
else:
print("Congratulations, you guessed right. The number was " + str(chosen_number) + ".")
break
answer = input("Do you want to play again? Y/N ")
if answer in ("Y", "y", "yes"):
print("Starting again")
else:
print("Goodbye!")
gameOn = 0
The loop will automatically restart if you don't change any of the variables. So I would change your if else statement to just an if statement that says:
if answer.lower() != "y" or answer.lower() != "yes":
break
but in order for the game to be re-run properly and change the random number variable you need to re-execute the entire program which you can do by putting the program in a function then putting the function and the if statement in that loop for example:
import random
def runGame():
random_number = random.randrange(0, 500)
chosen_number = int(input("Please pick a number: "))
running = True
while running:
if chosen_number == 500 or chosen_number <= 0 :
print("Number must be below 500 and above 0.")
print(random_number)
chosen_number = int(input("Please pick a number: "))
continue
if chosen_number > random_number:
print("Too high")
chosen_number = int(input("Please pick a number: "))
elif chosen_number < random_number:
print("Too low")
chosen_number = int(input("Please pick a number: "))
else:
print("Congratulations, you guessed right. The number was " + str(chosen_number) + ".")
break
while gameOn == 1:
runGame()
answer = input("Do you want to play again? Y/N ")
if answer.lower() != "y" or answer.lower() != "yes":
gameOn = 0
Related
The question is to check the guess entered as the input to the random number generator,
Here is my code for that,
import random
int1 = 1
int2 = 50
correctNumber = random.randint(1, 50)
a =int(input("Please enter your number: "))
while True:
if a > correctNumber:
print("LOW")
a = int(input("Please enter again : "))
elif a < correctNumber:
print("HIGH")
a = int(input("Please enter again : "))
elif a == correctNumber:
print("YOU GOT IT RIGHT")
break
The loop breaks after one cycle,
This solves the problem:
import random
int1 = 1
int2 = 50
correctNumber = random.randint(1, 50)
a =int(input("Please enter your number: "))
while True:
if a > correctNumber:
print("LOW")
a = int(input("Please enter again : "))
elif a < correctNumber:
print("HIGH")
a = int(input("Please enter again : "))
elif a == correctNumber:
print("YOU GOT IT RIGHT")
break #break used inside elif to loop while correct is not provided
Your booleans seem backward to me. When if a > correctNumber: the the guess is "HIGH" not "LOW".
With that, instead of breaking. You could make your while loop condition based on whether the guess is correct.
import random
int1 = 1
int2 = 50
correctNumber = random.randint(int1, int2)
a = int(input("Please enter your number: "))
while a != correctNumber:
if a < correctNumber:
print("LOW")
elif a > correctNumber:
print("HIGH")
a = int(input("Please enter again : "))
print("YOU GOT IT RIGHT")
If you are using a recent version of python, you can simplify it even further by assigning in the while loop with the := (walrus) operator:
import random
int1 = 1
int2 = 50
correctNumber = random.randint(int1, int2)
while (a := int(input("Please enter your number: "))) != correctNumber:
print("LOW" if a < correctNumber else "HIGH")
print("YOU GOT IT RIGHT")
Indent the break statement from the final line.
The break keyword is used to break out of the while loop. At its current state, the loop is terminating after 1 cycle because it hits the break keyword.
If you indent the break statement, it will be part of the elif block of code, and will only execute after a == correctNumber.
This code would work:
import random
correctNumber = random.randint(1, 50)
a =int(input("Please enter your number: "))
while True:
if a > correctNumber:
print("LOW")
a = int(input("Please enter again : "))
elif a < correctNumber:
print("HIGH")
a = int(input("Please enter again : "))
elif a == correctNumber:
print("YOU GOT IT RIGHT")
break
Learn more about break here
I am a newbie and need help to include a "last try" phrase after 4 of the 5 tries and a try-except element. I searched through past questions but I am still stuck with this code:
import random
random_number = random.randrange(0,20)
print(random_number)
print("Guess a number in the range 0-20. You have five tries.")
guess = False
while guess == False:
user_input = int(input("Your guess? "))
if user_input == random_number:
guess = True
print("Congratulations! Your guess is correct! It is " + str(random_number) + "!")
elif user_input > random_number:
print("The number is too high.")
elif user_input < random_number:
print("The number is too low.")
elif user_input < 5:
try:
guess = int(input("This is your last guess: "))
except ValueError:
print("Sorry. Your guesses are incorrect. The right answer is " + str(random_number) + ".")
print("End of program")
OK
I got it
This is updated one!
import random
def main():
random_number = random.randrange(0,20)
print(random_number)
print("Guess a number in the range 0-20. You have five tries.")
number_of_tries = 0
guess = False
while guess == False and number_of_tries < 5:
number_of_tries = number_of_tries + 1
print()
try:
user_input = int(input("Your guess? "))
except ValueError:
print("Your guess cannot be converted into an integer")
if user_input == random_number:
guess = True
print("Congratulations! Your guess is correct! It is " + str(random_number) + "!")
elif user_input > random_number:
print("The number is too high.")
elif user_input < random_number:
print("The number is too low.")
if (number_of_tries == 5):
print()
print("This is your last try")
try:
user_input = int(input("Your guess? "))
except ValueError:
print("Your guess cannot be converted into an integer")
print()
if (number_of_tries == 5 and guess == False):
print("Your guesses are incorrect. The right answer is " + str(random_number))
print("End of program")
print()
if __name__ == "__main__":
main()
Got a little help...
import random
def main():
random_number = random.randrange(0,20)
print(random_number)
print("Guess a number in the range 0-20. You have five tries.")
number_of_tries = 0
guess = False
while guess == False and number_of_tries < 5:
number_of_tries += 1
if (number_of_tries == 5):
print("This is your last try")
try:
user_input = int(input("Your guess? "))
except ValueError:
print("Your guess cannot be converted into an integer")
continue
if user_input == random_number:
guess = True
print("Congratulations! Your guess is correct! It is " + str(random_number) + "!")
elif user_input > random_number:
print("The number is too high.")
elif user_input < random_number:
print("The number is too low.")
if (number_of_tries == 5 and guess == False):
print("Your guesses are incorrect. The right answer is " + str(random_number))
print("End of program")
if __name__ == "__main__":
main()
I want my code to end after "thank you for playing", however underneath it, i get the message going back to "Guess my number:". I appreciate the help and advice! Thank you
def guess_number():
import random
import sys
guessesTaken = 0
max_number = float(input("What should the maxium number be for this game be? "))
print("")
number = random.randint(1,max_number)
while (guessesTaken) < 100000:
guesses = float(input("Guess my number: "))
guessesTaken = guessesTaken + 1
if guesses < number:
print("Your guess is too low.")
print("")
elif guesses > number:
print("Your guess is too high.")
print("")
elif guesses == number:
print("You guessed my number!")
print("")
again = (input("Do you wish to play again? (Y/N): "))
print("")
if again.lower() == "y":
guess_number()
else:
print("")
print("Thank you for playing!")
Instead of print("thank you for playing") try return "Thank you for playing!"
Why does the too low, too high and got it print repeatedly lots of times?
This is my code:
import random
name = input("Hello there! What's your name?\n")
print("Hello there", name, ". Welcome to GUESS THE NUMBER GAME")
number = random.randint(1,100)
guess = int(input("Please guess a number"))
n=1
while n<10:
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
elif guess == number:
print("Got it")
n=n+1
You need to move the guess inside the loop, from:
guess = int(input("Please guess a number"))
n=1
while n<10:
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
elif guess == number:
print("Got it")
n = n+1
to:
n = 1
while n < 10:
guess = int(input("Please guess a number"))
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
elif guess == number:
print("Got it")
n += 1
Also, you can simplify with:
for _ in range(9):
guess = int(input("Please guess a number"))
...
And should break when the user makes a correct guess:
elif guess == number:
print("Got it")
break
Is this your real indentation ?
if yes:
while n<10:
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
elif guess == number:
print("Got it")
and the last elif guess == number: can be just else ;)
edit: and I have forgotten your n++ and the real problem: the input
so:
while n<10:
guess = int(input("Please guess a number"))
n = n+1
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
else:
print("Got it")
and to exit the loop:
while n<10:
guess = int(input("Please guess a number"))
n = n+1
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
else:
print("Got it in "+n+" attempts.")
n=11
Assuming the code you provided has the correct indentation, then it's because the n = n + 1 statement is outside of the while loop. The corrected code is:
import random
name = input("Hello there! What's your name?\n")
print("Hello there", name, ". Welcome to GUESS THE NUMBER GAME")
number = random.randint(1,100)
guess = int(input("Please guess a number"))
n=1
while n<10:
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
elif guess == number:
print("Got it")
n=n+1
One piece of advice (assuming you're using Python 2.X): Use raw_input() instead of input, because raw_input automatically parses the input into a string, while input allows your users to inject arbitrary python code.
ETA: As pointed out by others, the guess statement (guess = int(input("Please guess a number"))) should be moved into the while loop, and a break statement used if the guess is correct.
This code:
import random
print("\tWelcome to the guess my number program\n")
print("im thinking of a number between 1 and 100")
print("try to guess it in 5 attempts\n")
randomNum = random.randint(1,101)
tries = 0
userNumber = int(input("please pick a number"))
while userNumber != randomNum:
if userNumber > randomNum:
print ("lower")
else:
print("higher")
tries += 1
print ("you guessed it! the number was" , randomNum)
For some reason this produces an infinite loop. Any help, im still getting used to python.
You never updated your userNumber or randomNum inside the while loop. So once the loop condition is met, it will execute infinitely.
You need to update your while loop as:
while userNumber != randomNum:
if userNumber > randomNum:
print ("lower")
else:
print("higher")
tries += 1
userNumber = int(input("please pick a number"))
You've forgotten to ask the user to guess again. Try this!
while userNumber != randomNum:
if userNumber > randomNum:
print("lower")
else:
print("higher")
tries += 1
userNumber = int(input("please pick a number")
Try This:
import random
print("Welcome to the guess my number program!")
randomnum = random.randint(1, 100)
print("I'm thinking of a number between 1 and 100.")
print("Try to guess it in 5 attempts.")
tries = 0
usernumber = 0
while not usernumber == randomnum:
usernumber = int(raw_input("please pick a number.")
if usernumber > randomnum:
print("Too High")
if usernumber < randomnum:
print("Too Low")
tries = tries + 1
if usernumber == randomnum:
print("You got the number!")
print("It took you " + str(tries) + " attempts.")