gpt4 book ai didi

python - 如何在函数循环之外定义参数?

转载 作者:行者123 更新时间:2023-12-04 08:43:47 25 4
gpt4 key购买 nike

我正在尝试执行一个函数,如果在我的 while 语句中看到正确的输入,该函数将重复。但是我的程序在附加循环中返回相同的值而没有选择使用新的 hrsrate如果我的输入语句高于我的函数,则输入。如果它们在当前呈现的函数内,它会说明我的 (hrs,rate)没有定义。 我将如何定义 hrsrate参数同时保持我的输入在函数内?

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)

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!')

最佳答案

首先,您需要在函数之后初始化两个变量,因此每当您输入变量的值时,它们都必须被定义。
类似的东西 :

# 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)

关于python - 如何在函数循环之外定义参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64431874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com