0

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 i.e., "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
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 3
    When you hit the `except`, it doesn't go back and ask for the hours and rate again. Thus, `rate_float` never actually gets assigned. – Green Cloak Guy May 29 '20 at 15:38
  • Try using `try/except/else` – SiHa May 29 '20 at 15:39
  • 1
    Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Tomerikoo May 29 '20 at 15:54
  • Can you please show me how to do it in my scenario? Would appreciate it! And the person who has posted his answer isn't working for me. It's showing me the same error. – Fiona Daniel May 29 '20 at 16:10
  • I took the advice of Tomerikoo and made it fit for you @Fiona Daniel – Thingamabobs May 29 '20 at 16:32
  • @Atlas435 Thank you so much. I have one another question on the following link if you can have a look at it. I would appreciate it. https://stackoverflow.com/questions/62099961/try-except-issue-in-python – Fiona Daniel May 30 '20 at 09:04
  • @Tomerikoo Thank you so much. Can you have a look at the following link. I would apprecaite it. https://stackoverflow.com/questions/62099961/try-except-issue-in-python – Fiona Daniel May 30 '20 at 09:05
  • @Tomerikoo How can the below code (written by @atlas435) be solved in a function form? Like def function? Your leads would be appreciated. – Fiona Daniel May 31 '20 at 21:07
  • Just put the code under a `def f():`..... I believe you would achieve much more by researching and reaching the solutions yourself than asking for every small detail. Have a look in the [tutorial](https://docs.python.org/3/tutorial/index.html), it's a great place to start... – Tomerikoo May 31 '20 at 21:23

3 Answers3

2

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)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Thingamabobs
  • 7,274
  • 5
  • 21
  • 54
  • How does this in any way answer the question as asked? The `NameError` is not occuring in the `try` block, but on line 9, after the `except` has already executed. Making the exception more specific does absolutely nothing to resolve the OP's problem. – Mihai Chelaru May 29 '20 at 15:53
  • He wanted to give the User a hint what hes doing wrong. Of course there can be more exeptions and maybe its needed to split the code in some steps, but I think he get it. If he would need for more support he could ask. – Thingamabobs May 29 '20 at 15:59
  • @Atlas435 Have you tried to run this new code after the edit? How is the program ever supposed to exit the first `while True:` loop? The condition will always be `True` and therefore it will run infinitely unless some uncaught exception terminates it prematurely. – Mihai Chelaru May 29 '20 at 17:23
  • @MihaiChelaru edited again. Thanks for your hint, I didnt mind. – Thingamabobs May 29 '20 at 17:59
  • @Atlas435 Thank you so much. I have a question. How can this question be solved in a function form? Like def function? – Fiona Daniel May 31 '20 at 21:07
  • @MihaiChelaru Thanks. I have a question. How can this question be solved in a function form? Like def function? – Fiona Daniel May 31 '20 at 21:09
  • @FionaDaniel I answered your Question in the other question you made up. I think you should stay in a one of these. I recommand also to try to solve the chellanges out of your book with the given code in there. The author want to make sure you did understand the lesson. I dont know if its helpful to do it for you. – Thingamabobs Jun 01 '20 at 09:15
0
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.

MarianD
  • 13,096
  • 12
  • 42
  • 54
  • Thank you so much. How can you achieve this target like if you enter string for hours and then it should directly get you printed that it's an invalid input instead of moving for the rate user prompted input? – Fiona Daniel May 31 '20 at 21:14
  • And how can this question be solved in a function form? Like def function? – Fiona Daniel May 31 '20 at 21:15
0

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.

Gustavo
  • 668
  • 13
  • 24
  • Thank you so much. How can you achieve this target like if you enter string for hours and then it should directly get you printed that it's an invalid input instead of moving for the rate user prompted input? – Fiona Daniel May 31 '20 at 21:13
  • Well I am setting the variable `userin = None` and while it is not what I want it to be it will keep asking for it. Notice the `while userin is None` will keep running the code if the result is not the expected, then the `var_type(userin)` is trying to cast the `int` or `float` type to the variable. If the cast is successful the function returns the user input and if not it assigns the value `None` to the `usering` variable again so it won't leave the while loop. – Gustavo Jun 01 '20 at 12:24