I have this code running in a number guessing game I have written, it runs perfectly fine if the player follows the instructions, but as we all know users never do. If the user enters just a space or any string thats not the word hint then it crashes saying invalid literal for int() with base 10: when trying to convert the value of guess to an integer. Is there any way around this or am I just going to have to live with the crashes?
while repeat==1:
repeat=0
level1number=str(level1number)
guess=input("What is your guess? ")
guess=guess.lower()
if guess==level1number:
print("Well done, You have guessed my number!")
elif guess=="hint":
print("Hints are not available until level 3")
repeat=1
elif guess!=level1number:
print("Sorry that is not my number, you have lost a life. :(")
lives=lives-1
repeat=1
if lives<=0:
print("You have lost all your lives, so this means I win")
print("The program will now end")
exit()
input("")
level1number=int(level1number)
guess=int(guess)
if guess<level1number:
print("The target number is higher")
else:
print("The target number is lower")
Use something as
if guess.isdigit() ...
(method isdigit() returns true if and only if all characters of a given string are digits, i.e. 0 to 9).
while repeat==1:
repeat=0
level1number=str(level1number)
guess=input("What is your guess? ")
guess=guess.lower()
if guess==level1number:
print("Well done, You have guessed my number!")
elif guess=="hint":
print("Hints are not available until level 3")
repeat=1
elif guess!=level1number:
print("Sorry that is not my number, you have lost a life. :(")
lives=lives-1
repeat=1
if lives<=0:
print("You have lost all your lives, so this means I win")
print("The program will now end")
exit()
input("")
level1number=int(level1number)
try:
guess=int(guess)
if guess<level1number:
print("The target number is higher")
else:
print("The target number is lower")
except:
print("Try again. Not a number")
Using try/except block would solve your problem. Have a look
Edit: In the question. you mentioned that you get an error when something other than a number is entered. Actually, it is an exception that is thrown when your code tries to convert your input string to a number when it is not possible(guess = int(guess)) due to the input not being a number, just like a space. So, what my code does, is that it catches the exception, and does not allow the program to terminate with the exception.
Just try it once. I know you are beginner but it is better to learn about exception handling as soon as possible, before you write more and more complex codes and applications.
Hope it helps!!
Related
I've run into a bug where the program seems to think that my input into an input statement isn't within the parameters, when it clearly is.
This is the code i'm having trouble with:
time.sleep(1.5)
print()
print()
print("You have chosen", horsechoice)
time.sleep(1)
print("How much do you want to bet?")
while True:
try:
moneyinput = int(input())
racebegin(moneyinput)
break
except:
print("Not a valid amount of money.")
continue
Even when I input an integer, it still states that I didn't input a valid amount of money.
If you only want to check the input validity, you should wrap the try/except only around the int(input()) call, not racebegin(). Your code is probably catching an error in racebegin().
It's also a good idea to narrow down the type of error you're catching with except:. Doing that might have prevented the problem in the original code, unless racebegin() was also raising ValueError.
while True:
try:
moneyinput = int(input())
break
except ValueError:
print("Not a valid amount of money.")
racebegin(moneyinput)
I am brand new to programming and I'm building a guessing game for fun as a first program. I've already figured out the following:
How to set a specific number for them to guess between 1-50 (for example)
What happens when they guess outside the parameters
Number of guesses and attempts to "break the game"
Included while loops full of if statements
What I can't seem to figure out though is how to stop the user from inputting anything other than a number into the game. I want them to be able to, but I'd like to print out a personal error message then exit the while loop. (Essentially ending the game).
This is as close as I've been able to guess:
if guess == number:
print('Hey wait! That\'s not a number!')
print('Try again tomorrow.')
guessed = True
break
I get the error: "ValueError: invalid literal for int() with base 10" and I'm clueless on how to figure this out. I've been reading about isdigit and isalpha and have tried messing around with those to see what happens, but I get the same error. Maybe I'm just putting it in the wrong section of code
Any hints? :)
Thank you!
Use try/except to handle exceptions:
try:
guess = int(input("What's your guess? "))
except ValueError:
print("Hey wait! That's not a number!")
print("Try again tomorrow.")
guessed = True
break
# otherwise, do stuff with guess, which is now guaranteed to be an int
You can use a try / except to attempt the cast to an integer or floating point number and then if the cast fails catch the error. Example:
try:
guessInt = int(guess)
except ValueError:
print('Hey wait! That\'s not a number!')
print('Try again tomorrow.')
guessed = True
break
I have recently started to program in Python. Now im working on a number guessing game. I have a proplem with understanding how does storing a random number works.I have looked around here, found some answer but couldnt make it work. The code works fine, but my answer (random number) is always different, so its imposible to guess it.
If anybody could help me or improve my code i would be glad.
Here is the part of that code where i have it:
def game(self):
import random
answer = random.randint(0, 1000)
guess = int(input("Your tip is:"))
while True:
if guess < answer:
print ("Your tip is lower, than the answer! Try again.")
self.game()
elif guess > answer:
print ("Your tip is bigger than the answer! Try again.")
self.game()
elif guess == answer:
print ("Good job! You have found the answer!")
self.replay()
That's because you are calling self.game() inside each if statement, which brings the execution flow back to the start of the function and generates a new number each time with answer = random.randint(0, 1000).
So simply remove self.game() and let the function reach the end:
import random
def game(self):
answer = random.randint(0, 1000)
while True:
guess = int(input("Your tip is:"))
if guess < answer:
print ("Your tip is lower, than the answer! Try again.")
elif guess > answer:
print ("Your tip is bigger than the answer! Try again.")
elif guess == answer:
print ("Good job! You have found the answer!")
self.replay()
break
EDIT 1:
You should also move the line where the user inputs his guess inside the while loop so that the user can guess until he gets the correct answer. I also added break statements to exit the loop when he gets the correct answer instead of only print statements. You can read more about break here (answer code above now updated)
EDIT 2:
Another small detail since you're new to Python: you should place all your import statements at the top of your python module, it's python coding guidelines that you should follow to make your code more clear. You can read more here
I'm trying to check that what's entered at the input function is all alpha characters. Basically I want to ensure numbers are not entered. However when I type a number such as 4 nothing happens. I don't even see an exception error. Also if i type anything besides "take honey" or "open door" it doesn't start the bear_room function. Haaalp. Thanks in advance!
def bear_room():
print("there's a bear here")
print("the bear has a bunch of honey")
print("the fat bear is front of another door")
print("how are you going to move the bear?")
choice = str(input("(Taunt bear, take honey, open door?: "))
try:
if choice.isalnum() == False:
if choice == "take honey":
print("the bear looks at you then slaps your face off")
elif choice == "open door":
print("get the hell out")
else:
bear_room()
except Exception as e:
print(str(e))
print("numbers are not accepted")
bear_room()
bear_room()
There's nothing to trigger an exception because code-wise it's perfectly legitimate to enter a number. It will check choice.isalnum(), it will be True for a number, and then bear_room() will be recursively called. You want the else part to contain the printing that you've got in the exception, then just get rid of the exception handler.
You have a few problems here.
First, don't cast your input to an str. It is already coming in as a string from input.
Second, is that you will never raise an exception with how you are looking to catch the exception you are looking to catch, because your input is outside the try/except. Not only that, but you will not raise an exception if you enter something like abcd1234. That is still a valid string.
Bonus problem you have. Never catch an open Exception. Always be explicit with what kind of exception you want to catch. However, you don't need to do a try/except here. Instead, just check if you have valid entries and proceed with your logic.
Simply, remove your try/except and even your isalnum check, and just check if the string entered matches what you are looking for. If it does not, output some kind of error message:
def bear_room():
print("there's a bear here")
print("the bear has a bunch of honey")
print("the fat bear is front of another door")
print("how are you going to move the bear?")
choice = input("(Taunt bear, take honey, open door?: ")
if choice == "take honey":
print("the bear looks at you then slaps your face off")
elif choice == "open door":
print("get the hell out")
else:
print("Invalid entry")
bear_room()
bear_room()
import random
def get_num ():
return random.randrange (999,9999)
print ("{}".format (get_num ()))
def get_user_input():
while True:
user_input = input
print("Please enter a four digit number")
return user_input
if False:
print ("Length of string:" , len (str))
Here in this piece of coding I am trying to make a random 4 digit number which will tell user whether or not s/he has guessed the right number (essentially),
specifically though: It will tell the user (at the end of the game) if s/he has guessed certain digits correctly but not which position.
I want 'break' statement to be fitted into this which will separate the while block from the if False. How do I do this correctly? I have tried maany times but I have 4 problems:
1- I don't know where to insert the break
2- When I run the program it doesn't print the second print function.
3- When I run the program it doesn't tell me the length of the string so I don't know if the user is even enterring the correct number of digits.
4- How do I set a limit on python (i.e. how many goes a player can have before the game ends?
I guess you are new to programming and this may be one of your very first codes. It would be great if you start by learning syntax of programming language which you have decided to use as well as working of loops, return statements, etc. I personally preferred reading any basic programming language book. For your case, it would be any book of python which is for beginners. For the sake of completeness, i have added the below code which is probably not exactly what you asked for:
import random
def get_num():
return random.randrange (999,9999)
def get_user_input():
user_input = int(input())
return user_input
while True:
comp_num = get_num()
print("The computer gave: {}".format(comp_num))
print("Your turn:")
user_num = get_user_input()
if user_num == comp_num:
print("Done it!")
break
else:
print("No, it's different. Try again!")
print()
In the above code, there are two functions and a while loop. One of the functions takes input from the user while the other generates a random number. The while loop is set to run for infinite iterations in case the user doesn't give the same input as the computer. As soon as the user gives the same input as the computer (which is displayed on the screen before he is asked to give input), the if condition evaluates to true, some things are printed and the break statement breaks the loop. And since, there is no further code, the program terminates