2 回答

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
首先,您需要在函數(shù)之后初始化這兩個(gè)變量,因此每當(dāng)您輸入變量的值時(shí),都必須定義它們。
像這樣的東西:
# those two lines will be after the function
hrs = 0
rate = 0
完整的程序?qū)⑷缦滤荆?
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貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超6個(gè)贊
在 while 循環(huán)中,您調(diào)用CalPay并傳入hrsand rate。您正在調(diào)用一個(gè)函數(shù)并為其提供在函數(shù)內(nèi)部創(chuàng)建的兩個(gè)值,即當(dāng)您調(diào)用 時(shí)它們不存在CalPay,因此您會(huì)收到錯(cuò)誤。只需在 while 循環(huán)中收集輸入,而不是在函數(shù)內(nèi)部收集輸入。像這樣:
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!')
注意:您必須相應(yīng)地調(diào)整重復(fù)程序的邏輯。
另一個(gè)更好的解決方案是從 CalPay 和函數(shù)調(diào)用中刪除參數(shù),然后收集函數(shù)內(nèi)所需的信息。正如阿努拉格所提到的。
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!')
添加回答
舉報(bào)