Try/except Issue In Python
Solution 1:
Ideally, you put as less code as possible into a try
-block and try to not repeat code, this makes it easier to debug/find errors in programs.
A more pythonic version of the 'questioning' would look like this:
# define a dictionary to save the user input
userInput = {
'hours': None,
'rate': None
}
# The input lines are identical so you can just 'exchange' the question.# Dynamically ask for user input and quit immedialy in case of non-floatfor question in userInput.keys():
try:
userInput[question] = float(input(f"Enter {question}:"))
except:
print('Error, please enter numeric input')
quit()
# continue with the original code
fh, fr = userInput['hours'], userInput['rate']
if fh > 40:
reg = fr * fh
otp = (fh - 40.0) * (fr * 0.5)
xp = reg + otp
else:
xp = fh * fr
print("Pay:", xp)
Solution 2:
I think the easiest way is this:
whileTrue: #open a while looptry: #ask your questions here
sh = input("Enter hours:")
fh = float(sh)
sr = input("Enter Rate:")
fr = float(sr)
except ValueError: #if a string is in input instead of a float do thisprint("input is not numeric")
else: # if user did all right do this and end the while loopprint(fh, fr)
if fh > 40:
reg = fr * fh
otp = (fh - 40.0) * (fr * 0.5)
xp = reg + otp
else:
xp = fh * fr
print("Pay:",xp)
break
edit:
defcheck_for_float(question):
#define a function to check if it's floatwhileTrue:
#open a while looptry:
#ask your questions here
value = float(input(question))
#return valuereturn value
except ValueError:
#if a string is in input instead of a float give second chanceprint("input is not numeric, try again:")
#execute function and give argument question#returned value will be your variable
fr = check_for_float("Enter Rate:")
fh = check_for_float("Enter hours:")
#do your stuff with the returned variablesprint(fh, fr)
if fh > 40:
reg = fr * fh
otp = (fh - 40.0) * (fr * 0.5)
xp = reg + otp
else:
xp = fh * fr
print("Pay:",xp)
all in one:
defcalculate_userinput ():
## function in function#this means the function check_for_float isn't available outside of calculatedefcheck_for_float(question):
#define a function to check if it's floatwhileTrue:
#open a while looptry:
#ask your questions here
value = float(input(question))
#return valuereturn value
except ValueError:
#if a string is in input instead of a float give second chanceprint("input is not numeric, try again:")
#execute function and give argument question#returned value will be your variable
fr = check_for_float("Enter Rate:")
fh = check_for_float("Enter hours:")
#do your stuff with the returned valuesprint(fh, fr)
if fh > 40:
reg = fr * fh
otp = (fh - 40.0) * (fr * 0.5)
xp = reg + otp
else:
xp = fh * fr
print("Pay:",xp)
calculate_userinput()
functions for diffrent stuff to use
defcheck_for_float(question):
#define a function to check if it's floatwhileTrue:
#open a while looptry:
#ask your questions here
value = float(input(question))
#return valuereturn value
except ValueError:
#if a string is in input instead of a float give second chanceprint("input is not numeric, try again:")
defcalculate():
fr = check_for_float("Enter Rate:")
fh = check_for_float("Enter hours:")
print(fh, fr)
if fh > 40:
reg = fr * fh
otp = (fh - 40.0) * (fr * 0.5)
xp = reg + otp
else:
xp = fh * fr
print("Pay:",xp)
calculate()
programming is like engineering, first you need to know what you want to create then how you get there in the best way. Wich structure you want, are there subsystems what they need to do or to watch et cetera.
Solution 3:
You have to put the check if the entered input is a number after every input statement.
try:
sh = input("Enter hours:")
fh = float(sh)
sr = input("Enter Rate:")
fr = float(sr)
except:
print('Error, please enter numeric input')
In your example you are getting both inputs and then check both of them. And to your question, I personally would prefer to only put the code that probabla produces errors in the try-statement, like you did.
Solution 4:
The problem with your code is that you are first taking both the variables sh
and sr
as input. So, even if you don't enter a numeric value it won't throw an error because the variables sh
and sr
don't care if it is a numeric value or not. After getting both the values the try block is executed.
So, if you want to receive an error message as soon as the user enters any alphabetic input, follow the below modified code. You can comment any doubts. Also, Tick the answer if it is correct.
try:
fh = float(input('Enter hours:'))
fr = float(input('Enter Rate:'))
except:
print('Error, please enter numeric input')
quit()
print(fh, fr)
if fh > 40:
reg = fr * fh
otp = (fh - 40.0) * (fr * 0.5)
xp = reg + otp
else:
xp = fh * fr
print("Pay:",xp)
The output for the test case forty
is
Enterhours:FortyError, please enter numeric input
Solution 5:
Updated ans :
import sys
sh = input("Enter hours:")
try:
fh = float(sh)
except:
print(f"{sh} is not numeric")
sys.exit(0)
sr = input("Enter Rate:")
try:
fr = float(sr)
except:
print(f"{sr} is not numeric")
sys.exit(0)
Post a Comment for "Try/except Issue In Python"