简体   繁体   中英

How can I get print except statement printed instead of an error below in try/except syntax in Python

I am new to Python programming. Following is the code written and it works fine when I print any numeric digit and give me the desired result as expected but the problem comes when I enter string (anything other than integer/float) instead of giving me just the except statement, it also gives me an error which I don't want. So, what I want is when a user enter anything other than numeric digits, he should be prompted with a message ie, "Invalid input. Enter a number please" instead of an error which I am getting after the except print statement in the end. Please help.

hours_string = input("Enter Hours: ")
rate_string = input("Enter Rate: ")
try:
    hours_float = float(hours_string)
    rate_float = float(rate_string)
except:
    print("Invalid input. Enter a number please.")

result = hours_float * rate_float
print("Pay",result)

This is the error I am getting. If I enter string, I should simply get an except statement. That's it. Not any other error. How can I accomplish to get there?

Enter Hours: 9
Enter Rate: entered string by mistake
Invalid input. Enter a number please.
Traceback (most recent call last):
  File "<string>", line 9, in <module>
NameError: name 'rate_float' is not defined

For a particular Error you can do a particular Exeption like in the Code below. Also note that each question is in a whileloop that you need to acomplish the task before you get to the next one.

while True:
    try:
        hours_string = input("Enter Hours: ")
        hours_float = float(hours_string)
    except ValueError:
        print("Invalid input. Enter a number please.")
    else:
        break
while True:        
    try:
        rate_string = input("Enter Rate: ")
        rate_float = float(rate_string)
    except ValueError:
        print("Invalid input. Enter a number please.")
    else:
        break

result = hours_float * rate_float
print("Pay",result)
hours_float = None
rate_float = None

while hours_float is None:
    hours_string = input("Enter Hours: ")
    try:
        hours_float = float(hours_string)
    except ValueError:
        print("Invalid input. Enter a number please.")

while rate_float is None:
    rate_string = input("Enter Rate: ")
    try:
        rate_float = float(rate_string)
    except ValueError:
        print("Invalid input. Enter a number please.")

result = hours_float * rate_float
print("Pay", result)

In the while loop we repeatedly ask user for input, while they don't enter a valid number, separately for hours and rate.

Valid input changes the initially set None value to something else, which finishes the corresponding loop.

Since this is a expected situation and it can be treated as a test I would recommend instead of trying to execute the operation with wathever input the user provided you could ask the user for the input and while it is not an integer you ask for the input again.

def get_input(name, var_type):
  userin = None
  while userin is None:
    userin = input(f'Input {name}: ')
    try:
      userin = var_type(userin)
    except ValueError:
      print(f'{name} must be {str(var_type)}, not {str(type(userin))}')
      userin = None
  return userin


hours = get_input('hours', int)
rate = get_input('rate', float)

result = hours * rate
print('Pay', result)

The function get_input tries to cast the input input value to the type you want and if it is not as desired it will keep asking until the type matches.

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