While loop won't end after second input "No" - python

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!"

Related

How can I make my program repeat execute many times?

I have a program that works fine, however I need to make it so that it can execute again when the if statement regarding playing again is satisfied.
import random
n=random.randint(0,10)
print(n)
number= int(input('Guess what the number is'))
count=0
while number !=n:
count=count+1
number= int(input('Guess what the number is'))
if number< n:
print("that is too low")
elif number>n:
print("That is too high")
else:
print("You got it right in"+ " "+str(count+1)+" "+ "tries")
print(count+1)
yesorno= str(input('Do you want to play again? y or n'))
if yesorno=="y":
number= int(input('Guess what the number is'))
elif yesorno=="n":
print("Goodbye")
If you don't want an ugly big while loop, use functions. It makes your code cleaner.
import random
def play():
input("Guess a number between 1 and 10: ")
random_number = random.randint(1, 10)
guess = None
attempts = 0
while guess != random_number:
guess = int(input("Pick a number from 1 to 10: "))
attempts += 1
if guess < random_number:
print("TOO LOW!")
elif guess > random_number:
print("TOO HIGH!")
print("YOU GOT IT! The number was {}, you got it in {} attempts.".format(random_number, attempts))
def main():
play()
while input("Play again? (y/n) ").lower() != "n":
play()
main() # Call the main function
import random
n=random.randint(0,10)
count = 0
while True:
count=count+1
number= int(input('Guess what the number is'))
if number< n:
print("that is too low")
elif number>n:
print("That is too high")
else:
print("You got it right in"+ " "+str(count)+" "+ "tries")
print(count)
yesorno= str(input('Do you want to play again? y or n'))
if yesorno=="y":
n=random.randint(0,10)
count = 0
elif yesorno=="n":
print("Goodbye")
break
import random
n=random.randint(0,10)
print(n)
count=0
while True:
count=count+1
number= int(input('Guess what the number is '))
if number< n:
print("that is too low")
elif number>n:
print("That is too high")
elif number == n:
print("You got it right in"+ " "+str(count+1)+" "+ "tries")
print(count+1)
yesorno= str(input('Do you want to play again? y or n'))
if yesorno=="n":
print("Goodbye")
break
Use a while loop with a condition that will always be true, like while True:.
To stop this infinite loop, use the break statement within the while loop.
If user inputs "y", the loop will continue because it has not been told the break.

While loop breaking after first nested question

I'm trying to get my program to work. It's a number guessing game where a user inputs their name, and then the program generates a number 1-100. From there they have to guess the number and the program tells them if their number is higher or lower.
If the user succeeded in guessing the number they have the option to play again. I've programmed this but it breaks after the first number input. Any idea where I went wrong?
import random
#importing the randoms
#getting the name from the user
message=("What is your name?")
name=input(message)
#challange message from user
print("Hello! ", name,"I have a number from 1 to 100! It is your job to try and guess it!")
gamestat=False
while gamestat==False:
#generate number
number = random.randint(1,101)
#start the game
guess = int(input("start to guess: "))
#GAME LOGIC
num_guesses = 1
while guess != number:
if guess > number:
print("lower")
guess = int(input("try again: "))
num_guesses +=1
if guess < number:
print ("higher")
guess = int(input("start to guess: "))
num_guesses +=1
print("congrats it took you", num_guesses, "tries")
message=("Would you like to play again? (yes or no)")
result=input(message)
if result == "no":
gamestat= True
Program indentation is not correct. Try using
import random
#importing the randoms
#getting the name from the user
message=("What is your name?")
name=input(message)
#challange message from user
print("Hello! ", name,"I have a number from 1 to 100! It is your job to try and guess it!")
gamestat=False
while gamestat==False:
#generate number
number = random.randint(1,101)
#start the game
guess = int(input("start to guess: "))
#GAME LOGIC
num_guesses = 1
while guess != number:
if guess > number:
print("lower")
guess = int(input("try again: "))
num_guesses +=1
if guess < number:
print ("higher")
guess = int(input("start to guess: "))
num_guesses +=1
print("congrats it took you", num_guesses, "tries")
message=("Would you like to play again? (yes or no)")
result=input(message)
if result == "no":
gamestat= True
Happy Coding!
As a comment already mentioned, it's an indentation issue.
if guess < number:
print ("higher")
guess = int(input("start to guess: "))
num_guesses +=1
This block is intended one tab to far, it resides under if guess > number and can thus never be reached.
Change your while loop to
while not gamestat:
# you can just invert it, same result as comparing to False
number = random.randint(1, 101)
# add some try except logic here and in the other inputs if the user doesn't input an int
guess = int(input("start to guess: "))
num_guesses = 1
while guess != number:
if guess > number:
print("lower")
guess = int(input("try again: "))
num_guesses += 1
if guess < number:
print("higher")
guess = int(input("start to guess: "))
num_guesses += 1
Here is your code after minor modifications.
One was indentation issue as pointed righty. Apart from this in guess< number block the message was start to guess which is not consistent with above which may cause ambiguity. Also you can remove the common part outside the if block.
import random
# importing the randoms
# getting the name from the user
message = ("What is your name?")
name = input(message)
# challange message from user
print("Hello! ", name, "I have a number from 1 to 100! It is your job to try and guess it!")
gamestat = False
while not gamestat:
# generate number
number = random.randint(1, 101)
# start the game
guess = int(input("start to guess: "))
# GAME LOGIC
num_guesses = 1
while guess != number:
if guess > number:
print("lower")
if guess < number:
print("higher")
guess = int(input("try again: "))
num_guesses += 1
if number == guess:
print("congrats it took you", num_guesses, "tries")
message = ("Would you like to play again? (yes or no)")
result = input(message)
if result == "no":
gamestat = True

Python Random number guesser problem with loops

I have built a random number guessing game for practice, but I am having some trouble with the final steps. When outputted, the game works as expected, however, I want it to ask the user if they want to play again after every guessing turn, with 'yes' meaning the game keeps going and 'exit' meaning the game stops. As of now, the game asks the user to guess the number, tells user if said number does not match, and then asks if they want to play, then it just repeats the guessing part, without asking if the user wants to play again. This is not what I want, as I would like to know how to properly write this code.
Here is my program:
import random
guess = int(input("Guess the number => "))
rand = random.randrange(1,10)
print("The number was", rand)
def guess_rand(guess, rand):
if rand == guess:
print("You have guessed right!")
elif rand > guess:
print("You guessed too low!")
elif guess > rand:
print("You guessed too high!")
guess_rand(guess, rand)
again = input("Would you like to try again? => ")
while again.lower() == 'yes':
guess = int(input("Guess the number => "))
rand = random.randrange(1,10)
print("The number was", rand)
guess_rand(guess, rand)
if again.lower() == 'exit':
break
Also, if there are any tips on how to keep track of how many guesses the user has taken, and when the game ends, to print them out, I would appreciate that. Thank you.
You are missing the statement to take user input again in the while loop:
again = input("Would you like to try again? => ")
while again.lower() == 'yes':
guess = int(input("Guess the number => "))
rand = random.randrange(1,10)
print("The number was", rand)
guess_rand(guess, rand)
again = input("Would you like to try again? => ")
if again.lower() == 'exit':
break
For keeping the count, you can add a new variable and increment in the while loop.
Here is what you asked and i also added turns to track the player
import random
turns = 0
def quit():
i = input ("Do you want to play again? if yes enter Yes if not Enter No\n")
if (i.lower() not in ["yes","no"]):
print ("Invalid input")
return True
if (i.lower() == "yes"):
print ("You choose to play")
return False
else:
print ("Thankyou for playing")
return True
while True:
guess = int(input("Guess the number => "))
rand = random.randrange(1,10)
print("The number was", rand)
def guess_rand(guess, rand):
if rand == guess:
print("You have guessed right!")
elif rand > guess:
print("You guessed too low!")
elif guess > rand:
print("You guessed too high!")
guess_rand(guess, rand)
if quit():
print("You have used",turns,"trun(s)")
break
else:
turns += 1
continue
I just added the "again" line of code in while loop and added an else statement
import random
guess = int(input("Guess the number => "))
rand = random.randrange(1,10)
print("The number was", rand)
def guess_rand(guess, rand):
if rand == guess:
print("You have guessed right!")
elif rand > guess:
print("You guessed too low!")
elif guess > rand:
print("You guessed too high!")
guess_rand(guess, rand)
again = input("Would you like to try again? => ")
while again.lower() == 'yes':
guess = int(input("Guess the number => "))
rand = random.randrange(1,10)
print("The number was", rand)
guess_rand(guess, rand)
again = input("Would you like to try again? => ")
if again.lower() == 'exit':
break
else:
continue

Keep a game going until the user types exit, and print out how many guesses the user did?

I need to generate a random number from 1 to 9 and ask the user to guess it. I tell the user if its too high, low, or correct. I can't figure out how to keep the game going until they guess it correctly, and once they get it right they must type in exit to stop the game. I also need to print out how many guesses it took for them in the end. Here's my code so far:
import random
while True:
try:
userGuess = int(input("Guess a number between 1 and 9 (including 1 and 9):"))
randomNumber = random.randint(1,9)
print (randomNumber)
except:
print ("Sorry, that is an invalid answer.")
continue
else:
break
if int(userGuess) > randomNumber:
print ("Wrong, too high.")
elif int(userGuess) < randomNumber:
print ("Wrong, too low.")
elif int(userGuess) == randomNumber:
print ("You got it right!")
import random
x = random.randint(1,9)
print x
while (True):
answer=input("please give a number: ")
if ( answer != x):
print ("this is not the number: ")
else:
print ("You got it right!")
break
Here is the solution for your problem from:
Guessing Game One Solutions
import random
number = random.randint(1,9)
guess = 0
count = 0
while guess != number and guess != "exit":
guess = input("What's your guess?")
if guess == "exit":
break
guess = int(guess)
count += 1
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
else:
print("You got it!")
print("And it only took you",count,"tries!")
from random import randint
while 1:
print("\nRandom number between 1 and 9 created.")
randomNumber = randint(1,9)
while 1:
userGuess = input("Guess a number between 1 and 9 (including 1 and 9). \nDigit 'stop' if you want to close the program: ")
if userGuess == "stop":
quit()
else:
try:
userGuess = int(userGuess)
if userGuess > randomNumber:
print ("Wrong, too high.")
elif userGuess < randomNumber:
print ("Wrong, too low.")
else:
print ("You got it right!")
break
except:
print("Invalid selection! Insert another value.")

Issue with simple Guess the number game in python

I have an issue with my simple guess the number game in python.The code is given below.The program never gives me a correct guess,it keep asking the number.
import random
import time
time1 = time.time()
number = random.randint(1,1000)
print ("welcome to the guessing game")
name = input("what is your name? ")
print("well, " + name + " iam thinking of the number between 1 and 1000")
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
if guess < number:
print("too low!")
if guess == number:
break
print("yahoo,you guessed the number!")
input()
time2 = time.time()
that is number guessing game in python 3.
You need to indent the code correctly, you should also use if/elif's as guess can only be one of higher, lower or equal at any one time. You also need to print before you break on a successful guess:
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
elif guess < number:
print("too low!")
elif guess == number:
print("yahoo,you guessed the number!")
time2 = time.time()
break
There is no way your loop can break as your if's are nested inside the outer if guess > number:, if the guess is > number then if guess < number: is evaluated but for obvious reasons that cannot possibly be True so you loop infinitely.
import random
import time
time1 = time.time()
number = random.randint(1,1000)
print ("welcome to the guessing game")
name = input("what is your name? ")
print("well, " + name + " i am thinking of the number between 1 and 1000")
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
if guess < number:
print("too low!")
if guess == number:
print("yahoo,you guessed the number!")
time2 = time.time()
break
without changing too much, here is a working code.
secret_number = 5
chance = 1
while chance <= 3:
your_guess = int(input("Your Guess:- "))
chance = chance + 1
if your_guess == secret_number:
print("You Won !!")
break
else:
print("You failed..TRY AGAIN..")
import random as rand
# create random number
r =rand.randint(0,20)
i=0
l1=[]
while(i<4):enter code here
number = int(input("guess the number : "))
if(number in l1):
print("this number is alraedy entered")
i=i
else:
l1.append(number)
if(number == r):
print(number)
break
if(number>r):
print(" number is less than your number ")
elif(number<r):
print("number is greater than your number")
i =i+1
print("number is")
print(r)

Categories

Resources