Python exception user input - python

Hi i'm new to python and i am having issues with exceptions. i have added an exception but it is not working. Below is a sample of my problem.
if x == '1':
print("----------------------------------")
print("1. REQUEST FOR A DOG WALKER")
print("----------------------------------")
try:
print("Select a Date (DD/MM/YY) - eg 12/04/21")
except ValueError:
raise ValueError('empty string')
date = input()
try:
print("Select a Duration (in hours) - eg 2")
duration = input()
except ValueError:
print('empty string')
print("Select a breed : 1 - Rottwieler , 2 - Labrador Retriever, 3 - Pitbull, 4 - Other ")
breed = input()
print("Number of Dogs - eg 3 ")
dogsNumber = input()

Whenever you use a try/except statement you are trying to catch something happening in the code the shouldn't have happened. In your example, you are haveing the user enter a number for a duration:
print("Select a Duration (in hours) - eg 2")
duration = input()
At this point, duration might equal something like '2'. If you wanted to add 10 to it then you could not because it is a string(you cannot and int+str). In order to do something like this, you would have to convert the user input to an int. For example:
duration = int(input())
The problem is that if the user enters a letter A, then the program will break when it tries to convert it to an int. Using a try/except statement will catch this behavior and handle it properly. For example:
try:
print("Select a Duration (in hours) - eg 2")
duration = int(input())
except ValueError:
print('empty string')

There is nothing in your code that can produce ValueError.
So the except ValueError: is not matched.

1 - You are not checking any conditions to raise the error
2 - You're not catching the ValueError, you have to raise it and then catch in with the except statement.
Try this:
if x == '1':
print("----------------------------------")
print("1. REQUEST FOR A DOG WALKER")
print("----------------------------------")
print("Select a Date (DD/MM/YY) - eg 12/04/21")
try:
date = input()
if len(date) == 0:
raise ValueError('empty string')
except ValueError as error:
print(error)

Related

Try-Except ErrorCatching

I'm trying to force the user to input a number using try-except in python however it seems to have no effect.
while count>0:
count=count - 1
while (length != 8):
GTIN=input("Please enter a product code ")
length= len(str(GTIN))
if length!= 8:
print("That is not an eight digit number")
count=count + 1
while valid == False:
try:
GTIN/5
valid = True
except ValueError:
print("That is an invalid number")
count=count + 1
Actually, if the user inputs for example a string, "hello"/5 yields a TypeError, not a ValueError, so catch that instead
You could try to make the input value an int int(value), which raises ValueError if it cannot be converted.
Here's a function that should do what you want with some comments:
def get_product_code():
value = ""
while True: # this will be escaped by the return
# get input from user and strip any extra whitespace: " input "
value = raw_input("Please enter a product code ").strip()
#if not value: # escape from input if nothing is entered
# return None
try:
int(value) # test if value is a number
except ValueError: # raised if cannot convert to an int
print("Input value is not a number")
value = ""
else: # an Exception was not raised
if len(value) == 8: # looks like a valid product code!
return value
else:
print("Input is not an eight digit number")
Once defined, call the function to get input from the user
product_code = get_product_code()
You should also be sure to except and handle KeyboardInterrupt anytime you're expecting user input, because they may put in ^C or something else to crash your program.
product code = None # prevent reference before assignment bugs
try:
product_code = get_product_code() # get code from the user
except KeyboardInterrupt: # catch user attempts to quit
print("^C\nInterrupted by user")
if product_code:
pass # do whatever you want with your product code
else:
print("no product code available!")
# perhaps exit here

ValueError exception not working in python

I'm trying to make a simple program that will calculate the area of a circle when I input the radius. When I input a number it works, but when I input something else I'd like it to say "That's not a number" and let me try again instead of giving me an error.
I can't figure out why this is not working.
from math import pi
def get_area(r):
area = pi * (r**2)
print "A= %d" % area
def is_number(number):
try:
float(number)
return True
except ValueError:
return False
loop = True
while loop == True:
radius = input("Enter circle radius:")
if is_number(radius) == True:
get_area(radius)
loop = False
else:
print "That's not a number!"
When you don't input a number, the error is thrown by input itself which is not in the scope of your try/except. You can simply discard the is_number function altogether which is quite redundant and put the print statement in the except block:
try:
radius = input("Enter circle radius:")
except (ValueError, NameError):
print "That's not a number!"
get_area(radius)
radius is still a string,
replace
get_area(radius)
with
get_area(float(radius))
You also have to replace input with raw_input since you're using Python 2
in= 0
while True:
try:
in= int(input("Enter something: "))
except ValueError:
print("Not an integer!")
continue
else:
print("Yes an integer!")
break

ERROR-HANDLING not working

My error-handling code is not working. I'm trying to do following: if user enters any input other than 1, 2 or 3, then the user should get error message and the while-loop should start again.
However my code is not working. Any suggestion why?
def main():
print("")
while True:
try:
number=int(input())
if number==1:
print("hei")
if number==2:
print("bye")
if number==3:
print("hei bye")
else:
raise ValueError
except ValueError:
print("Please press 1 for hei, 2 for bye and 3 for hei bye")
main()
You can also use exception handling a bit more nicely here to handle this case, eg:
def main():
# use a dict, so we can lookup the int->message to print
outputs = {1: 'hei', 2: 'bye', 3: 'hei bye'}
print() # print a blank line for some reason
while True:
try:
number = int(input()) # take input and attempt conversion to int
print(outputs[number]) # attempt to take that int and print the related message
except ValueError: # handle where we couldn't make an int
print('You did not enter an integer')
except KeyError: # we got an int, but couldn't find a message
print('You entered an integer, but not, 1, 2 or 3')
else: # no exceptions occurred, so all's okay, we can break the `while` now
break
main()

Check Length of user input

Im trying to check the length of the string entered by the user and if its < 5 it goes through however no matter what length it still goes through my try except statement
print """
Please put in the Stock symbol for the Company
whose last closing stock price you wish to see."""
while True:
symbol = raw_input("Enter Stock Symbol: ")
try:
len(symbol) < 5
break
except ValueError:
print 'Greater than 4 characters, Try again'
print 'Great your stock symbol is less than 5'
You don't need a try/except:
while True:
symbol = raw_input("Enter Stock Symbol: ")
if len(symbol) > 4:
print 'Greater than 4 characters, Try again'
else:
print 'Great your stock symbol {} is less than 5'.format(symbol)
break
In [3]: paste
while True:
symbol = raw_input("Enter Stock Symbol: ")
if len(symbol) > 4:
print 'Greater than 4 characters, Try again'
else:
print 'Great your stock symbol {} is less than 5'.format(symbol)
break
## -- End pasted text --
Enter Stock Symbol: FOOBAR
Greater than 4 characters, Try again
Enter Stock Symbol: YHOO
Great your stock symbol YHOO is less than 5
In your code:
try:
len(symbol) < 5 # always checks len
break # always breaks
except ValueError:
You would use a try/except if for instance you wanted to cast the input to an int catching a ValueError there but it is not applicable in your case.
You must first call (TypeError or ValueError or ..Error) in try section in the if statement, and decide what to do with this error in the except section. More information: here
while True:
name = input (': ')
try:
if (len (name) >= 4):
raise ValueError()
break
except ValueError:
print ('Account Created')
else:
print ('Invalid Input')

Python 2.7 try and except ValueError

I query user input which is expected to be an int by using int(raw_input(...))
However when the user doesn't enter an integer, i.e. just hits return, I get a ValueError.
def inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue):
rowPos = int(raw_input("Please enter the row, 0 indexed."))
colPos = int(raw_input("Please enter the column, 0 indexed."))
while True:
#Test if valid row col position and position does not have default value
if rangeRows.count(rowPos) == 1 and rangeCols.count(colPos) == 1 and inputMatrix[rowPos][colPos] == defaultValue:
inputMatrix[rowPos][colPos] = playerValue
break
else:
print "Either the RowCol Position doesn't exist or it is already filled in."
rowPos = int(raw_input("Please enter the row, 0 indexed."))
colPos = int(raw_input("Please enter the column, 0 indexed."))
return inputMatrix
I tried to be smart and use try and except to catch the ValueError, print a warning to the user and then call the inputValue() again. Then it works when the user enters return to the query but falls over when the user correctly then enters an integer
Below is the part of the amended code with the try and except:
def inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue):
try:
rowPos = int(raw_input("Please enter the row, 0 indexed."))
except ValueError:
print "Please enter a valid input."
inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue)
try:
colPos = int(raw_input("Please enter the column, 0 indexed."))
except ValueError:
print "Please enter a valid input."
inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue)
A quick and dirty solution is:
parsed = False
while not parsed:
try:
x = int(raw_input('Enter the value:'))
parsed = True # we only get here if the previous line didn't throw an exception
except ValueError:
print 'Invalid value!'
This will keep prompting the user for input until parsed is True which will only happen if there was no exception.
Instead of calling inputValue recursively, you need to replace raw_input with your own function with validation and retry. Something like this:
def user_int(msg):
try:
return int(raw_input(msg))
except ValueError:
return user_int("Entered value is invalid, please try again")
Is something like this what you're going for?
def inputValue(inputMatrix, defaultValue, playerValue):
while True:
try:
rowPos = int(raw_input("Please enter the row, 0 indexed."))
colPos = int(raw_input("Please enter the column, 0 indexed."))
except ValueError:
continue
if inputMatrix[rowPos][colPos] == defaultValue:
inputMatrix[rowPos][colPos] = playerValue
break
return inputMatrix
print inputValue([[0,0,0], [0,0,0], [0,0,0]], 0, 1)
You were right to try and handle the exception, but you don't seem to understand how functions work... Calling inputValue from within inputValue is called recursion, and it's probably not what you want here.

Categories

Resources