This is probably very basic but I am trying to trigger the Except to run if cointype() is not within the dictionary coin_int but it jumps straight out of the if condition without using the Except even if a value error is met?
Thanks for any help.
try:
coin_type = input("Input your coin: 1p, 2p, 5p etc... ")
if coin_type in coin_int:
print("That value is recognised inside the list of known coin types")
except ValueError:
print("That value of coin is not accepted, restarting...")
you want to raise an exception. Just
raise ValueError("wrong coin type")
Firstly your except will never be reached... you don't "try" anything that will raise ValueError exception... Let me first show how to this, and then basically say that in this case you don't gain anything by using try/except:
coin_int = ("1p", "2p", "5p")
while True:
coin_type = input("Input your coin: 1p, 2p, 5p etc.: ")
try:
coin_int.index(coin_type)
print("value accepted, continuouing...")
break
except ValueError:
print("That value of coin is not accepted, try again and choose from", coin_int)
But this is equivalent and in this case just as efficient (if not better actually both in performance and readability):
coin_int = ("1p", "2p", "5p")
while True:
coin_type = input("Input your coin: 1p, 2p, 5p etc.: ")
if coin_type in coin_int:
print("value accepted, continuouing...")
break
else:
print("That value of coin is not accepted, try again and choose from", coin_int)
If you really want to stop program execution then do any of the following in the except:
raise to raise the excception caught with default message
raise ValueError("That value of coin is not accepted, try again and choose from", coin_int) which also can be used in the else to raise the specific exception with custom message
Your program should looks like this. (i am giving example through a list instead of dictionary)
coin_int = ['1p', '2p', '3p', '4p', '5p']
try:
coin_type = '6p'
if coin_type in coin_int:
print("That value is recognised inside the list of known coin types")
else:
raise ValueError("wrong coin type")
except ValueError as error:
print("That value of coin is not accepted, restarting..." + repr(error))
Related
I just made an intangible atm app. nothing fancy, you basically create an acct with an amount and can also withdraw. I'm trying to fix a Value error incase a user enters an alphabet in the Tkinter textbook instead of an integer.
I did the try catch statement but it still throws a Value error.
def get_selected_row(event):
try:
global selected_tuple
index = list1.curselection()[0]
selected_tuple= list1.get(index)
e1.delete(0,END)
e1.insert(END,selected_tuple[1])
e2.delete(0,END)
e2.insert(END,selected_tuple[2])
e3.delete(0,END)
e3.insert(END,selected_tuple[3])
e4.delete(0,END)
e4.insert(END,selected_tuple[4])
except ValueError:
pass
def acct_details ():
global balance
list1.delete(0,END)
list1.insert(END,("Hello", acct_name.get()))
list1.insert(END, ("your account number is ", acct_number.get()))
list1.insert(END, ("and your balance is", balance))
def clear():
list1.delete(0,END)
e1.delete(0,END)
e2.delete(0,END)
e3.delete(0,END)
def withdraw_fxn(amount):
list1.delete(0,END)
try:
global balance
if balance < amount:
list1.insert(END,('Sorry, you have an insufficient Balance'))
else:
balance = balance - amount
list1.insert(END, (acct_name.get(), "Your new balance is ",balance))
except ValueError:
pass
def deposit_fxn(amount):
list1.delete(0,END)
global balance
try:
balance += amount
list1.insert(END,(acct_name.get(), "your new balance is ", balance))
except ValueError:
pass
You are catching an IndexError, to catch a ValueError you must add
except ValueError:
...
Instead of catching an Value error incase user enters an alphabet, you can try putting an if condition after wherever you input the details and using the isalpha() method, you can check if any alphabet is entered, if yes, you can tell the user that and not accept that input.
Getting input from the user and convert it into the float, while getting the entry from the user and then I want to check if user press enter without giving any input or value then it will bring the user to again enter the marks.
while(True):
assign1=float(input("Please enter the marks: "))
if(assign1>100 or assign1<0):
continue
else:
marks=(assign1*20)/100
break
Use try/except to handle the exception. Please find below code. Hope it helps.
while(True):
try:
assign1=float(input("Please enter the marks: "))
except Exception as e:
print (e) ## do you stuff with error
else:
if(assign1>100 or assign1<0):
continue
else:
marks=(assign1*20)/100
break
i'd go with a try/except clause:
while(True):
try:
assign1=float(input("Please enter the marks: "))
except:
continue
if(assign1>100 or assign1<0):
continue
else:
marks=(assign1*20)/100
break
In this way, anything that raise an error when converted to float (including '', or Enter without giving any input) will result in he repetition of the question.
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
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
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()