User input Exit to break while loop - python

I'm doing an assignment for the computer to generate a random number and have the user input their guess. The problem is I'm supposed to give the user an option to input 'Exit' and it will break the While loop. What am I doing wrong? I'm running it and it says there's something wrong with the line guess = int(input("Guess a number from 1 to 9: "))
import random
num = random.randint(1,10)
tries = 1
guess = 0
guess = int(input("Guess a number from 1 to 9: "))
while guess != num:
if guess == num:
tries = tries + 1
break
elif guess == str('Exit'):
break
elif guess > num:
guess = int(input("Too high! Guess again: "))
tries = tries + 1
continue
else:
guess = int(input("Too low! Guess again: "))
tries = tries + 1
continue
print("Exactly right!")
print("You guessed " + str(tries) + " times.")

The easiest solution is probably to create a function that gets the displayed message as an input and returns the user input after testing that it fulfils your criteria:
def guess_input(input_message):
flag = False
#endless loop until we are satisfied with the input
while True:
#asking for user input
guess = input(input_message)
#testing, if input was x or exit no matter if upper or lower case
if guess.lower() == "x" or guess.lower() == "exit":
#return string "x" as a sign that the user wants to quit
return "x"
#try to convert the input into a number
try:
guess = int(guess)
#it was a number, but not between 1 and 9
if guess > 9 or guess < 1:
#flag showing an illegal input
flag = True
else:
#yes input as expected a number, break out of while loop
break
except:
#input is not an integer number
flag = True
#not the input, we would like to see
if flag:
#give feedback
print("Sorry, I didn't get that.")
#and change the message displayed during the input routine
input_message = "I can only accept numbers from 1 to 9 (or X for eXit): "
continue
#give back the guessed number
return guess
You can call this from within your main program like
#the first guess
guess = guess_input("Guess a number from 1 to 9: ")
or
#giving feedback from previous input and asking for the next guess
guess = guess_input("Too high! Guess again (or X to eXit): ")

You are trying the parse the string 'Exit' to an integer.
You can add a try/except around the casting line and handle invalid input.
import random
num = random.randint(1,9)
tries = 1
guess = 0
guess = input("Guess a number from 1 to 9: ")
try:
guess = int(guess) // try to cast the guess to a int
while guess != num:
if guess == num:
tries = tries + 1
break
elif guess > num:
guess = int(input("Too high! Guess again: "))
tries = tries + 1
continue
else:
guess = int(input("Too low! Guess again: "))
tries = tries + 1
continue
print("Exactly right!")
print("You guessed " + str(tries) + " times.")
except ValueError:
if guess == str('Exit'):
print("Good bye")
else:
print("Invalid input")

Related

How to loop a simple game to continue until user stops it not using a break?

def set_number():
import random
return random.randint(1,500)
#This function plays the game
def number_guessing_game(number):
guess_counter = 0
guess = int(input("Enter a number between 1 and 500."))
while guess != number:
guess_counter += 1
if guess > number:
print(f"You guessed too high. Try Again!")
guess = int(input("Enter a number between 1 and 500."))
elif guess < number:
print(f"You guessed too low. Try Again!")
guess = int(input("Enter a number between 1 and 500."))
if guess == number:
print(f"You guessed the number! Good Job.!")
again = str(input("would you like to play again? Enter 'y' for yes or 'n' to close the game."))
def main():
print(f"Welcome to the Number Guessing Game!\n" +
f"You will have unlimited guesses. The number is between 1 and 500.\n" +
f"Good Luck!")
number = set_number()
guess_count = number_guessing_game(number)
main()
I am working on a simple game project for my coding class. I am not good at coding at all. I came up with this part of the program, I just cannot figure out how to loop the entire number_guessing_game function until the user enters 'n' to stop it, I can't use a break because we did not learn it in the class and I will receive a 0 if I use a break.
I tried nesting a while loop inside of the function but I know I did it wrong.
Instead of using break use return.
def main():
print(f"Welcome to the Number Guessing Game!\n" +
f"You will have unlimited guesses. The number is between 1 and 500.\n" +
f"Good Luck!")
while True:
number = set_number()
number_guessing_game(number)
again = input("would you like to play again? Enter 'y' for yes or 'n' to close the game.")
if again == 'n':
return
main()
You will probably want to remove the last line of the number_guessing_game function if you use this approach
First, your code is assuming the return of input is an integer that can be converted with int(). If you were to give it 'n' your program will crash.
Instead you could use the string class method isdigit() to see if the input was an integer value and then make a logical decision about it. Also note you do not need to convert the return from input to a str() as it is already a str type. You can confirm this with a print(type(input("give me something")))
guess = input("Enter a number between 1 and 500. 'n' to quit"))
if guess.isdigit():
[your code to check the value]
elif ('n' == guess):
return
else:
print(f"You entered an invalid entry: {guess}. Please re-enter a valid value")
If you dont like the idea of using 'return' you could change your while loop to look something like:
while(('n' != guess) or (guess != number)):
If you want the function body looping continuously you could have some code like:
def number_guessing_game(number):
exit_game = False
guess_counter = 0
while(exit_game != True):
guess = input("Enter a number between 1 and 500.))
guess_counter += 1
if guess.isdigit():
if int(guess) > number:
print("You guessed too high. Try Again!")
elif int(guess) < number:
print("You guessed too low. Try Again!")
elif int(guess) == number:
print("You guessed the number! Good Job.!")
again = input("would you like to play again? Enter 'y' for yes or 'n' to close)
if ('n' == again):
exit_game = True
else:
print("Error, please enter a valid value")

Crashing when improper input given more than once

I'm trying to make a simple number guesser program, it works pretty well however if I enter 'a' twice instead of a valid int it crashes out. Can someone explain what I'm doing wrong here.
import random
def input_sanitiser():
guess = input("Please enter a number between 1 and 10: ")
while True:
if type(guess) != int:
guess = int(input("That isn't a number, try again: "))
elif guess not in range (1,11):
guess = int(input("This is not a valid number, try again: "))
else:
break
def main():
number = random.randrange(1,10)
guess = 0
input_sanitiser()
while guess != number:
if guess < number:
print("This number is too low!")
input_sanitiser()
if guess > number:
print("This number is too high!")
input_sanitiser()
else:
break
print ("Congratulations, you've guessed correctly")
if __name__ == "__main__":
main()
You want to check the input before trying to convert it to int:
int(input("This is not a valid number, try again: "))
I would write:
while True:
try:
guess = int(input("This is not a valid number, try again: "))
except ValueError:
pass
else:
break
Side note: the code isn't working as expected:
def main():
number = random.randrange(1,10)
guess = 0
input_sanitiser() # <<<<<<<<<<
while guess != number:
Note that input_sanitiser does not modify the variable guess in main, you need some other way round, like processing the input then returning the result from input_sanitiser, like this:
def input_sanitiser():
guess = input("Please enter a number between 1 and 10: ")
while True:
try:
guess = int(input("This is not a valid number, try again: "))
except ValueError:
continue # keep asking for a valid number
if guess not in range(1, 11):
print("number out of range")
continue
break
return guess
def main():
number = random.randrange(1,10)
guess = input_sanitiser()
while guess != number:
if guess < number:
print("This number is too low!")
guess = input_sanitiser()
if guess > number:
print("This number is too high!")
guess = input_sanitiser()
else:
break
print ("Congratulations, you've guessed correctly")

In my guess the number it tells me my Number variable isnt defined

With my guess the number program, when I try to run it tells me the the variable "number" is not defined. I would appreciate it and be thankful if someone came to my aid in this!
import random
guesses = 0
def higher(guesses):
print("Lower")
guesses = guesses + 1
def lower(guesses):
print("Higher")
guesses = guesses + 1
def correct(guesses):
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_(guesses):
print("Welcome to guess the number")
number = random.randint(1, 100)
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher(guesses)
elif guess < number:
lower(guesses)
elif guess == number:
correct(guesses)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
break
elif answer == "N":
exit()
else:
exit()
_main_(guesses)
Your problem is that number is not defined in the function correct. number is defined in _main_. When you call correct in _main_, it does not get access to number.
This is the fixed version of your code:
import random
guesses = 0
number = random.randint(1, 100)
def higher(guesses):
print("Lower")
guesses = guesses + 1
def lower(guesses):
print("Higher")
guesses = guesses + 1
def correct(guesses):
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_(guesses):
print("Welcome to guess the number")
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher(guesses)
elif guess < number:
lower(guesses)
elif guess == number:
correct(guesses)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
break
elif answer == "N":
exit()
else:
exit()
_main_(guesses)
What I changed is I moved the definition of number to the top, which allowed it to be accessed by all functions in the module.
Also, your code style is not very good. Firstly, do not name your main function _main_, instead use main. Additionally, you don't need a function to print out 'lower' and 'higher.' Here is some improved code:
import random
def main():
number = random.randint(1, 100)
guesses = 0
while True:
guessed_num = int(input('Guess the number: '))
guesses += 1
if guessed_num > number:
print('Guess lower!')
elif guessed_num < number:
print('Guess higher!')
else:
print('Correct!')
print('The number was {}'.format(number))
print('It took you {} guesses.'.format(guesses))
break
main()
Your specific problem is that the variable number is not defined in function correct(). It can be solved by passing number as an argument to correct().
But even if you correct that problem, your program has another major issue. You have defined guesses globally, but you still pass guesses as an argument to lower(), higher() and correct(). This creates a duplicate variable guesses inside the scope of these functions and each time you call either of these functions, it is this duplicate variable that is being incremented and not the one you created globally. So no matter how many guesses the user takes, it will always print
You took 1 guesses.
Solution:
Define the functions lower() and higher() with no arguments. Tell those functions thatSo ultimately this code should work:
import random
guesses = 0
def higher():
global guesses
print("Lower")
guesses = guesses + 1
def lower():
global guesses
print("Higher")
guesses = guesses + 1
def correct(number):
global guesses
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_():
print("Welcome to guess the number")
guesses = 0
number = random.randint(1, 100)
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher()
elif guess < number:
lower()
elif guess == number:
correct(number)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
_main_()
elif answer == "N":
exit()
else:
exit()
_main_()

Guessing game: matching user input with randomly generated number

def var (guess):
return guess
guess = int(input("Guess a number 1 through 10: "))
import random
num = (random.randint(1,10))
while True:
try:
guess = num
print("you guessed the right number!")
break
except:
print("try again")
break
So for this program I am trying to figure out how to have the user input a number and to guess what number (1 through 10) the program generated. It seems that every time I input a value it always gives me the "you guess the right number!" string even if I input a value higher than 10.
EDIT: Why would someone downvote my question o_o
You need to get user's input inside while loop so that user's input got updated with each iteration.
import random
num = (random.randint(1,10))
while True:
try:
guess = int(input("Guess a number 1 through 10: "))
if guess == num:
print("you guessed the right number!")
break
else:
print("try again")
except:
print('Invalid Input')
try/except is for exception handling, Not matching values. What you are looking for is if statments, For example:
guess = int(input("Guess a number 1 through 10: "))
import random
num = (random.randint(1,10))
if guess == num:
print("You guessed the right number!")
else:
print("Try again")
I think you may have intended to continue looping until the right number is guessed, In which case, This will work:
import random
num = (random.randint(1,10))
while True:
guess = int(input("Guess a number 1 through 10: "))
if guess == num:
print("You guessed the right number!")
break
else:
print("Try again")

Python 3.4 :While loop not looping

Python loop isn't wanting to loop back if the user's guess is greater than or less than the randomly generated value. It either exits the loop or creates an infinite loop. Where am I going wrong?
import random
correct = random.randint(1, 100)
tries = 1
inputcheck = True
print("Hey there! I am thinking of a numer between 1 and 100!")
while inputcheck:
guess = input("Try to guess the number! " )
#here is where we need to make the try statement
try:
guess = int(guess)
except ValueError:
print("That isn't a number!")
continue
if 0 <= guess <= 100:
inputcheck = False
else:
print("Choose a number in the range!")
continue
if guess == correct:
print("You got it!")
print("It took you {} tries!".format(tries))
inputcheck = False
if guess > correct:
print("You guessed too high!")
tries = tries + 1
if guess < correct:
print("You guessed too low!")
tries = tries + 1
if tries >= 7:
print("Sorry, you only have 7 guesses...")
keepGoing = False
The problem is with this line:
if 0 <= guess <= 100:
inputcheck = False
This will terminate the loop whenever the user enters a number between 0 and 100. You can rewrite this part as:
if not 0 <= guess <= 100:
print("Choose a number in the range!")
continue
The correct code is below:
import random
correct = random.randint(1, 100)
tries = 1
inputcheck = True
print("Hey there! I am thinking of a numer between 1 and 100!")
while inputcheck:
guess = input("Try to guess the number! " )
#here is where we need to make the try statement
try:
guess = int(guess)
except ValueError:
print("That isn't a number!")
continue
if 0 > guess or guess > 100:
print("Choose a number in the range!")
continue
if guess == correct:
print("You got it!")
print("It took you {} tries!".format(tries))
inputcheck = False
if guess > correct:
print("You guessed too high!")
tries = tries + 1
if guess < correct:
print("You guessed too low!")
tries = tries + 1
if tries > 7:
print("Sorry, you only have 7 guesses...")
inputcheck = False
The problem here was that you were setting inputcheck to False when the value of guess was in between 0 and 100. This changed the value of while to False and the loop was exiting since while wasn't True anymore.
Also, you should change the last if case in the while loop since this now fixes the case of running indefinitely:
if tries > 7:
print("Sorry, you only have 7 guesses...")
inputcheck = False

Categories

Resources