Why does this not work?

def paycheck():
    hours=input("Enter hours: ")
    rate=input("Enter rate: ")
    print("Enter numeric values only, please retry.")
print("Pay: ",pay)

What do you mean exactly? Do you get some error?

When I run the code, python ignores the try step and goes directly to the except. Even after that, I get an error message saying "TypeError: float() argument must be a string or a real number, not ‘NoneType’ ".

Could you paste the full traceback with the error?

The code you provided has several issues. Let’s go through them step by step:

  1. In Python, function definitions require a colon : at the end, but the paycheck() function definition is missing it. Update the code to include the colon at the end of the def paycheck(): line.
  2. The try-except block is not correctly indented. In Python, proper indentation is crucial for defining blocks of code. Indent the code under the try block to ensure it is inside the block. Similarly, indent the code under the except block.
  3. In the line fp=float(paycheck()), you’re trying to convert the result of the paycheck() function to a float. However, the paycheck() function doesn’t return any value. Instead, it prompts for input and calculates the pay internally. You need to modify the function to return the calculated pay.
  4. Inside the except block, when you print the error message, you call paycheck() again. This will create an infinite recursion, repeatedly prompting for input if an exception occurs. Instead, you can use the return statement to exit the function after printing the error message.
  5. After the except block, you have code that calculates the pay using float(hours) and float(rate). However, hours and rate are defined within the paycheck() function and not accessible outside the function. To address this, you need to modify the function to return the hours and rate as well.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.