简体   繁体   中英

try/except issue in Python

I ran the following code as a practice purpose from one of the Python book and I want the output as shown in the URL provided below. So, when I am running the first activity in the question (from book - shown in the photo) to verify if he has done it correctly, it's working but when he ran the second activity, it's not working properly. Ideally, I should get except statement printed if I am entering any string in the first user prompted input but I am being asked for the second user prompted input ie, rate. Why is that so? And also please tell if it is advisable to put complete code in try portion or ideally we should only put the portion in a try statement for which we are sure that it wouldn't work out and it would jump to except block?

When I enter forty, I am not given the error message which is in the book which means that there can be some changes made in the code. However, it is working fine when I am including all lines of codes under try instead of just 2 lines which are currently there ie, (fh = float(sh) and fr = float(sr)). How can I correct my existing written code by just writing two statements in a try portion?

Your help would be appreciated.

Issue: Enter Hours: fortyError, please enter numeric input

Image of the required output is below: 在此处输入图像描述

Following is the code:

sh = input("Enter hours:")
sr = input("Enter Rate:")
try:
    fh = float(sh)
    fr = float(sr)
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)

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-float
for 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)

I think the easiest way is this:

while True:  #open a while loop
        try:  #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 this
            print("input is not numeric")
        else:  # if user did all right do this and end the while loop
            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)
            break

edit:

def check_for_float(question):
    #define a function to check if it's float
    while True:
        #open a while loop
            try:
                #ask your questions here
                value = float(input(question))
                #return value
                return value
            except ValueError:
                #if a string is in input instead of a float give second chance
                print("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 variables
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)

all in one:

def calculate_userinput ():
    ## function in function
    #this means the function check_for_float isn't available outside of calculate
    def check_for_float(question):
        #define a function to check if it's float
        while True:
            #open a while loop
                try:
                    #ask your questions here
                    value = float(input(question))
                    #return value
                    return value
                except ValueError:
                    #if a string is in input instead of a float give second chance
                    print("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 values
    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_userinput()

functions for diffrent stuff to use

def check_for_float(question):
    #define a function to check if it's float
    while True:
        #open a while loop
            try:
                #ask your questions here
                value = float(input(question))
                #return value
                return value
            except ValueError:
                #if a string is in input instead of a float give second chance
                print("input is not numeric, try again:")

def calculate():
    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.

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)

jupyter output

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.

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

Enter hours:Forty
Error, please enter numeric input

This python programme is not able to convert string to number so it is throwing a error. So yoy should use numeric in place string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM