I wanted to add an if/else to an except statement that checks for a specific input by the user (i.e "exit"). However the except statement is bound to Value Error. Running the below code gives me 2 error: Value Error and Name Error. The "user_guess" variable is not being identified in the except block, hence the Name error. I've tried using abstraction, i.e routing the data via a function called from the except statements block, however I still keep getting Name Error.
while (lives>0 and not found):
try:
user_guess=int(input(f"(Lives = {lives})Enter Your Guess: ").strip())
except ValueError:
if(user_guess == "exit"):
break
else:
raise (ValueError)
else:
if((user_guess)>guess):
print("Your guess is High. Try Something Lower. \n")
lives-=1
I would like to know how to implement the code such that the program throws the "Value Error" exception to all cases other than the one case i.e when the user inputs the word "exit" into the terminal. I'm using Python 3.6
As you said, you are trying to convert the input to integer as soon as you get it. Because of this you don't have an opportunity to compare it to "exit". So, instead, let us get and save the input as string, compare it to "exit", then try to convert it to an integer:
lives = 5
guess = 6
found = False
while lives > 0 and not found:
user_guess = input(f"(Lives = {lives})Enter Your Guess: ").strip()
if user_guess == "exit":
break
try:
user_guess_int = int(user_guess)
except ValueError:
print("Invalid input!")
else:
if user_guess_int > guess:
print("Your guess is High. Try Something Lower.")
lives -= 1
elif user_guess_int < guess:
print("Your guess is Low. Try Something Higher.")
lives -= 1
else:
print("Correct!")
found = True
Related
I am learning about the try and except statements now and I want the program to print out a message when a negative number is inserted but I don't know how to create the order of the statements for this output:
print("how many dogs do you have?")
numDogs= input()
try:
if int(numDogs)>=4:
print("that is a lof of dogs")
else:
print("that is not that many dogs")
except:
print("you did not enter a number")
I want the program to print tje output when the user enters a negative number.
How can I do it?
Just code is like
try:
if no<0:
print("no is negative ")
raise error
And further code will be as it is
Here is what you are trying to achieve.
class CustomError(Exception):
pass
print("how many dogs do you have?")
try:
numDogs = int(input())
if numDogs < 0:
raise CustomError
elif int(numDogs)>=4:
print("that is a lot of dogs")
else:
print("that is not that many dogs")
except CustomError:
print("No Negative Dogs")
except:
print("you did not enter a number")
You can start by creating a custom exception. See https://www.programiz.com/python-programming/user-defined-exception
After which, you should have a condition to first detect the negative value then raise an error from it.
Finally, You can then create multiple excepts to get different error. The first except is raised on input of negative values (as your condition will do for you) whereas the second is used to catch non valid value such as characters.
Note that your int(input) segment should be WITHIN your try block to detect the error
Solution I found is from this SO question
I want the program to print out a message when a negative number is inserted
You can raise a valueError like #Jackson's answer, or you can raise an Exception like in my code below.
elif numDogs < 0:
raise Exception("\n\n\nYou entered a negative number")
def main():
try:
numDogs= int(input("how many dogs do you have? "))
if numDogs >= 4:
print("that is a lot of dogs")
elif numDogs < 0:
raise Exception("\n\n\nYou entered a negative number")
else:
print("that is not that many dogs")
except ValueError:
print("you did not enter a number")
main()
One thing that I though I should point out is that its probably better practice to just check if the number is < 0 or is NAN. But like you said, you're trying to learn about the try and except statements. I thought it was cool that in this code segment:
try:
if numDogs < 0:
raise ValueError
except ValueError:
print("Not a negative Number")
you can throw what error you want and your try will catch it. Guess im still learning a lot too. Only part is, if that happens if your code then one won't know if its a negative number issue or if the number is something like "a", which cannot be converted to one (in this way).
All in all, I think its best to solve this problem with no try / except statements:
def main():
num_dogs = input("# of dogs: ")
if not num_dogs.isnumeric():
return "Error: NAN (not a number)"
num_dogs = int(num_dogs)
return ["thats not a lot of dogs", "that's a lot of dogs!"][num_dogs >= 4] if num_dogs > 0 else "You Entered a negative amount for # of dogs"
print(main())
Notice that I wrapped everything in a `main` function, because that way we can return a string with the result; this is important because if we get an error we want to break out of the function, which is what return does.
I'm warming-up with the Python and need your help regarding applying a few exceptions. This is a simple guessing game that a user enters input and tries to guess the random number generated. I'm trying to catch en exception where the user enters a number from 1 to 50.
To do so, I used IndexError. Is that the right error type I am using?
I also entered another exception, namely ValueError to prevent make sure that users enter a number, not whitespace.
My question is how can I throw an exception that the user enters a number only between 1 and 50?
import random
number_of_guesses = 0
number = random.randint(1,50)
name = input('Hi! Enter your name: ')
while number_of_guesses < 8:
try:
guess = input("Take a guess between 1 and 50 including ")
guess = int(guess)
number_of_guesses+=1
guesses_left = 8 - number_of_guesses
except IndexError:
print('Please enter a number only between 1 and 50 including')
continue
except ValueError:
print('Enter a number')
continue
if guess>number:
print('Your guess is higher than the actual number',guesses_left,'guesses left')
elif guess<number:
print('Your guess is lower than the actual number',guesses_left,'guesses left')
elif guess==number:
break
if guess==number:
print('Well done! You guessed the number in',number_of_guesses,'tries:')
if guess != number:
print('Sorry, the number I was thinking of was',number)
Welcome to SO and python
First, take a step back to understand what the try/except block does.
try/except is a construct where Python will "try" to execute a block of code and catch any exception (or unexpected error) by matching the type of Exception with error types specified by except clause(s).
An IndexError occurs when you attempt to index an object that supports indexing (eg a list) and the index you have specified is outside the range of the index for example:
my_list = ["a", "b", "c"]
print(mylist[0])
# will print "a"
print(my_list[4])
# with raise in IndexError as index 4 doesn't exist.
In your example, ValueError is raised by the call to int when a non-integer argument value is passed. Because you are not indexing anything IndexError is not raised.
As to placing if/else within or outside the try block. By placing it in the try block any exceptions raised in the if/else block are caught. In both cases, the behaviour of the if/else block remains the same.
For the index error you need to index a list
a = [1 , 2, 3]
print(a[5])
With placing statements inside the try you catch the exception(s) in your program and can handle the problem yourself so the program keeps running.
Outside the try results in an exception error and the program aborts.
I'm making a simple guessing game in python and was trying to create an "Invalid entry" message for when the user enters in any input that is not an integer.
I have tried to use just 'int' in an if statement to address all integers, but that is not working.
I know that I have the syntax wrong. I'm just not sure what the correct syntax to do it would be.
import random
play = True
while play:
count = 1
hidden = random.randrange(1,5)
guess = int(input("Guess a number between 1 and 5:"))
if guess != int
guess = int(input("Invalid Entry. Please enter an Integer between 1 and 5:"))
while guess != hidden:
count+=1
if guess > hidden + 10:
print("your guess is to high!")
elif guess < hidden -10:
print("your too low!")
elif guess > hidden:
print("your really warm, but still to high!")
elif guess < hidden:
print("your really warm, but still to low")
print("You have guessed incorrectly, Try again!. \n")
#reset the guess variable and make another guess
guess = int(input("Guess a number between 1 and 5:"))
print("Nice!!! Your guess was correct!\n you got the correct number in" , count , "tries.")
count = 1
playagain = str(input("Do you want to play again?\nType yes or no: "))
if playagain == "no" or "n" or "N" or "no thank you":
play = False
elif playagain == "yes" or "y" or "Y" or "YES" or "yes":
play = True
else: playagain != "yes" or "y" or "Y" or "YES" or "yes" "no" or "n" or "N" or "no thank you"
playagain = str(input("Invalid Entry. Please Type yes or no: "))
This is the error that I'm getting. There may be some other mistakes in my code as well.
File "comrandomguess.py", line 18
if guess != int
^
SyntaxError: invalid syntax
If you really want to verify that the user entry is an int, you want to keep the input in string form. Then write a small function to test the input. Here, I'll use a list comprehension and the string join and isdigit methods, to ensure the user has only entered digits 0-9 in the string, i.e. then this function returns True (else False) (*modified as per Jack Taylor comment below, also for s = '' case):
def testForInt(s):
if s:
try:
_ = s.encode('ascii')
except UnicodeEncodeError:
return False
test = ''.join([x for x in s if x.isdigit()])
return (test == s)
else:
return False
If you want to sandbox the user entirely, wrap it in a loop like this:
acceptable = False
while not acceptable:
entry = input("Enter an int: ")
if testForInt(entry):
entry = int(entry)
acceptable = True
else:
print("Invalid Entry")
If you want a simpler version with no function call(see Jack Taylor comment), this works too:
acceptable = False
while not acceptable:
entry = input("Enter an int: ")
try:
entry = int(entry)
acceptable = True
except ValueError as e:
print(f"Failed due to {str(e)}")
Now you've got what you know is an int, with no worries. This kind of approach to verifying user entry saves many headaches if consistently implemented. See SQL injection etc.
I always use this method to check if something is not an integer:
Python 3
if not round(guess) == guess: print("Do Stuff")
Python 2
if not round(guess) == guess: print "Do Stuff"
You need to do something like this:
play = True
while play:
guess = input("Guess a number between 1 and 5: ")
try:
number = int(guess)
except ValueError:
print("You need to input an integer.")
continue
if number < 1 or number > 5:
print("You need to input an integer between 1 and 5.")
continue
# ...
print("Your number was: " + guess)
play = False
When you first use input(), you get a string back. If you try to turn that string into an integer straight away by doing int(input()), and if the player types a string like "abcd", then Python will raise an exception.
>>> int(input("Guess a number: "))
Guess a number: abcd
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abcd'
To avoid this, you have to handle the exception by doing int(guess) inside a try/except block.
The continue statement skips back to the start of the while loop, so if you use it you can get away with only having to ask for input once.
Parse the user input as string to avoid ValueError.
guess = input("Guess a number between 1 and 5: ")
while not guess.isdigit() or int(guess) > 5 or int(guess) < 1:
guess = input("Invalid Entry. Please enter an Integer between 1 and 5: ")
guess = int(guess)
Above code ensures that user input is a positive integer and between 1 and 5. Next, convert the user input to integer for further use.
Additionally, if you want to check the data type of a python object/variable then use the isinstance method. Example:
a = 2
isinstance(a, int)
Output:
>>> True
I am trying to write a game that generates a random integer and the user has to guess it.
The problem is that if the user input is not a digit it crashes. So I tried to use isdigit, and it works at the beginning, but if the user decides to input not a number after the first input was a digit, it still crashes. I don't know how to make it check isdigit for every input.
import random
x =(random.randint(0,100))
print("The program draws a number from 0 to 100. Try to guess it!")
a = input("enter a number:")
while a.isdigit() == False :
print("It is not a digit")
a = input("enter a number:")
if a.isdigit() == True :
a = int(a)
while a != x :
if a <= x :
print("too less")
a = input("enter a number:")
elif a >= x :
print("too much")
a = input("enter a number")
if a == x :
print("good")
I would suggest doing the following:
completed = False
while not completed:
a = input("enter a number: ")
if a.isdigit():
a = int(a)
if a < x:
print("too little")
elif a > x:
print("too much")
else:
print("good")
completed = True
else:
print("It is not a digit")
If your code crashed because the user entered not a number, then either make sure the user enters a number, or handle an error while trying to compare it with a number.
You could go over all chars in the input and ensure that they are all digits.
Or you could use a try/except mechanism. That is, try to convert to the numerical type you wish the user to enter and handle any error throwen. Check this post:
How can I check if a string represents an int, without using try/except?
And also:
https://docs.python.org/3/tutorial/errors.html
The typical pythonic way to tackle that would be to "ask for forgiveness instead of looking before you leap". In concrete terms, try to parse the input as int, and catch any errors:
try:
a = int(input('Enter a number: '))
except ValueError:
print('Not a number')
Beyond that, the problem is obviously that you're doing the careful checking once at the start of the program, but not later on when asking for input again. Try to reduce the places where you ask for input and check it to one place, and write a loop to repeat it as often as necessary:
while True:
try:
a = int(input('Enter a number: '))
except ValueError: # goes here if int() raises an error
print('Not a number')
continue # try again by restarting the loop
if a == x:
break # end the loop
elif a < x:
print('Too low')
else:
print('Too high')
print('Congratulations')
# user vs randint
import random
computer = random.randint(0,100)
while True:
try:
user = int(input(" Enter a number : "))
except (ValueError,NameError):
print(" Please enter a valid number ")
else:
if user == computer:
print(" Wow .. You win the game ")
break
elif user > computer:
print(" Too High ")
else:
print(" Too low ")
I think this can solve the issues.
In your code you want to check whether the user has input no or string since your not using int() in your input it will take input as string and furthur in your code it wont be able to check for <= condition
for checking input no is string or no
code:-
a = input ("Enter no")
try:
val = int(a)
print("Yes input string is an Integer.")
print("Input number value is: ", a)
except ValueError:
print("It is not integer!")
print(" It's a string")
You probably will have to learn how to do functions and write your own input function.
def my_input(prompt):
val = input(prompt)
if val.isdigit():
return val
else:
print('not a number')
# return my_input(prompt)
New to stackoverflow, and new to python (python-3). Currently learning on edx.org and ran into the following error.
I created a function that checks a user-input str against the answer str and returns True or False.
When testing the function, I created a while loop to stop at the 3rd unsuccessful attempt. However, whenever there is an unsuccessful attempt, the function prints the error message twice when it should only print it once.
I fixed the error by storing the returning Bool value of the function into a variable rather than calling the function directly in the if condition within the while loop. However, I would like to understand the logic behind the error message printing twice. Here is the original code that prints the error message twice :
def letter_guess(letter, guess):
if len(guess) == 1 and guess.isalpha() and guess < letter:
print(guess,"is lower than the answer. Try again.\n")
return False
elif len(guess) == 1 and guess.isalpha() and guess > letter:
print(guess,"is higher than the answer. Try again.\n")
return False
elif len(guess) == 1 and guess.isalpha() and guess == letter:
print("Correct answer!")
return True
else:
print("Please only enter one alphabet for the letter. Try again.\n")
return False
answer2 = "m"
guess2 = input("Please enter a single alphabet : ")
i = 0
while i < 3:
if letter_guess(answer2, guess2):
break
elif letter_guess(answer2, guess2) == False and i == 2:
print("You have reached 3 guesses. Game over.")
break
else:
i += 1
guess2 = input("Please guess again : ")
You want to call input() inside the while loop:
# ...
answer2 = "m"
i = 0
while i < 3:
guess2 = input("Please enter a single alphabet : ")
# ...
Otherwise the user doesn't have a chance to change their answer, guess2 never changes and they get the same error message multiple times.
You call the function twice, in first if and in elif, with the same wrong guess. You fixed it right calling only once and storing the return value.
I try to explain it better: the function is always called by the first if, to evaluate its condition; if return value is false, is called again to evaluate the elif condition, with same arguments as before.