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!')
添加回答
舉報