def paycheck():
hours=input("Enter hours: ")
rate=input("Enter rate: ")
try:
fp=float(paycheck())
except:
print("Enter numeric values only, please retry.")
paycheck()
fh=float(hours)
fr=float(rate)
pay=fh*fr
#quit()
pay=float(hours)*float(rate)
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:
- 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 thedef paycheck():
line. - The
try-except
block is not correctly indented. In Python, proper indentation is crucial for defining blocks of code. Indent the code under thetry
block to ensure it is inside the block. Similarly, indent the code under theexcept
block. - In the line
fp=float(paycheck())
, you’re trying to convert the result of thepaycheck()
function to a float. However, thepaycheck()
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. - Inside the
except
block, when you print the error message, you callpaycheck()
again. This will create an infinite recursion, repeatedly prompting for input if an exception occurs. Instead, you can use thereturn
statement to exit the function after printing the error message. - After the
except
block, you have code that calculates the pay usingfloat(hours)
andfloat(rate)
. However,hours
andrate
are defined within thepaycheck()
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.