program says it isn't a valid input when it is - python

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)

Related

Not catching specific errors with Try and Except

Alright, so I've got a try and except block watching out for exceptions.
This is all normal but when you've got a loop you can't stop the code usually, as there's no specific bit saying "Don't catch KeyboardInterrupt errors" or something alike
Is there anything that let's try and except blocks exclude specific errors? (or an alternative)
My code
while 1:
if ques == 'n':
try:
newweight = int(input('Please enter a number'))
exit()
except:
print('Please enter a valid number')
Now this will create an infinite loop as the "exit()" will not happen as it will get raised an as exception, and it will thus create an infinite loop. Is there any way for this to not happen?
To prevent a user entering a non-integer value, you want to catch a TypeError so you can change except: to except ValueError: and it will then catch any invalid inputs. That should cover you sufficiently.

Is there any way to trigger an exception for incorrect string inputs in Python?

I am creating a text-to-speech synthesizer in Python. To allow maximum flexibility and user-friendliness, the program allows the user to edit variables, like speech rate or volume. I made a try-except-else loop to catch any wrong inputs. The problem with this is that the if an input is invalid, the exception is not triggered until later in the program. The inputs that are not being caught are strings. Is there any way to trigger an exception if certain keywords are not inputted, like:
while True:
try:
var = input("Choose your speech rate (Slow, Normal, or Fast): ")
except var != "Slow", "Normal", "Fast" :
print("\nPlease try again.")
continue
else:
break
Thanks!
You don't need to raise an exception. Just use an if/else statement instead.
Also, to check if var is either one of Slow, Normal or Fast, check it's membership on a set with those elements using the in keyword:
while True:
var = input("Choose your speech rate (Slow, Normal, or Fast): ")
if var not in {"Slow", "Normal", "Fast"}:
print("\nPlease try again.")
else:
break

Challenges with guessing game of integers

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

How to use isalpha to loop back when an alphabetical character isn't entered

I am a little confused as to why the loop ends. I was trying to make it so that if someone inputs numbers it loops back and asks the question again however it seems to just end. Any help would be greatly appreciated.
while True:
first_name = input("Please enter your first name. ")
try:
if first_name.isalpha() == False:
print("Please don't use alphanumeric characters ")
except:
if first_name.isalpha() == True:
print()
else:
break
The try-except-else and if-else blocks seem to be kind of mixed up. The except block will only be executed if an exception is thrown within the try: block body, and this doesn't happen normally in this code.
The else: block attached to try: will be executed every time the try: block *doesn't* throw an exception. So in this case it will execute thebreak` statement every time.

converting string to int crashing the program

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

Categories

Resources