2 回答
TA贡献1946条经验 获得超3个赞
首先,您需要在函数之后初始化这两个变量,因此每当您输入变量的值时,都必须定义它们。
像这样的东西:
# those two lines will be after the function
hrs = 0
rate = 0
完整的程序将如下所示:-
def CalPay(hrs,rate):
hrs = input('Please enter number of hours worked for this week:')
rate = input('What is hourly rate:')
try:
hrs = float(hrs)
except:
hrs = -1
try:
rate = float(rate)
except:
rate = -1
if hrs <= 0 :
print('You have entered wrong information for hours.')
elif rate <= 0 :
print('You have entered wrong rate information.')
elif hrs <= 40 :
pay = hrs * rate
print ('Your pay for this week is:', pay)
elif hrs > 40 and hrs < 60 :
pay = ((hrs - 40) * (rate * 1.5)) + (40 * rate)
print ('Your pay for this week is:', pay)
elif hrs >= 60 :
pay = ((hrs - 60) * (rate * 2.0)) + (20 * (rate * 1.5)) + (40 * rate)
print ('Your pay for this week is:', pay)
hrs = 0
rate = 0
while True:
CalPay(hrs,rate)
yn = input('Do you wish to repeat this program? (y/n)').lower()
if yn == 'y' :
continue
if yn == 'n' :
break
print ('Done!')
输出
Please enter number of hours worked for this week: 36
What is hourly rate: 6
Your pay for this week is: 216.0
Do you wish to repeat this program? (y/n)Y
Please enter number of hours worked for this week: 12
What is hourly rate: 5
Your pay for this week is: 60.0
Do you wish to repeat this program? (y/n)
TA贡献1799条经验 获得超6个赞
在 while 循环中,您调用CalPay并传入hrsand rate。您正在调用一个函数并为其提供在函数内部创建的两个值,即当您调用 时它们不存在CalPay,因此您会收到错误。只需在 while 循环中收集输入,而不是在函数内部收集输入。像这样:
while True:
hrs = input('Please enter number of hours worked for this week:')
rate = input('What is hourly rate:')
CalPay(hrs,rate)
yn = input('Do you wish to repeat this program? (y/n)').lower()
if yn == 'y' :
continue
if yn == 'n' :
break
print ('Done!')
注意:您必须相应地调整重复程序的逻辑。
另一个更好的解决方案是从 CalPay 和函数调用中删除参数,然后收集函数内所需的信息。正如阿努拉格所提到的。
def CalPay():
hrs = input('Please enter number of hours worked for this week:')
rate = input('What is hourly rate:')
try:
hrs = float(hrs)
except:
.
.
.
while True:
CalPay()
yn = input('Do you wish to repeat this program? (y/n)').lower()
if yn == 'y' :
continue
if yn == 'n' :
break
print ('Done!')
添加回答
举报