Can anybody helpe with this code? I am trying to loop the game after the question: "would you like to play again? " if the answer is yes.
import random
from random import randint
print ("Welcome to the number guessing game!")
seed_word = input("Enter random seed: ")
random.seed(seed_word)
print ("")
num = randint(1, 100)
guess = int(input("Please enter a guess: "))
count = 1
while num != "guess":
if guess < num:
print ("Higher")
print ("")
guess = int(input("Please enter a guess: "))
count = count + 1
elif guess > num:
print ("Lower")
print ("")
guess = int(input("Please enter a guess: "))
count = count + 1
else:
print ("Congratulations. You guessed it!")
print ("It took you " + str(count) + " guesses.")
print ("")
play_again = input("Would you like to play again (yes/no)? ")
if play_again == str("no") or play_again == str("No"):
break
if play_again == str("yes") or play_again == str("Yes"):
print (guess)
When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor ( </> ) to add backticks around text.
Hello.
Your issue was not only on the indent but also in your while loop condition.
-The only condition you needed to eval in order to keep it running until your user input a “No” was just True, since you already wrote a break condition.
-Since you were already using the variable num as a flag. U can see I added an if statement at the beginning of the loop to run your first lines of code. num will only be reassigned with “guess” once the user beats the game and input a “Yes” to keep playing.
import random
from random import randint
print ("Welcome to the number guessing game!\n")
num="guess"
while True:
if num == "guess":
seed_word = input("Enter random seed: \n")
random.seed(seed_word)
num = randint(1, 100)
guess = int(input("Please enter a guess: "))
count = 1
if guess < num:
print ("Higher\n")
guess = int(input("Please enter a guess: "))
count = count + 1
elif guess > num:
print ("Lower\n")
guess = int(input("Please enter a guess: "))
count = count + 1
else:
print ("Congratulations. You guessed it!")
print ("It took you " + str(count) + " guesses.\n")
play_again = input("Would you like to play again (yes/no)? ").lower()
if play_again == "no":
break
if play_again == "yes":
print (guess)
num="guess"
Tips:
a) “\n” stands for linebreak. You can split the same string into several lines or put blank lines as I did above.
b) str.lower() will lowercase the entire string. So user’s uppercase inputs are converted before the if statements.