gpt4 book ai didi

Python:错误处理递归函数错误

转载 作者:太空宇宙 更新时间:2023-11-03 12:00:31 26 4
gpt4 key购买 nike

这是我的第三个问题。由于堆栈溢出,我已经两次被选出该岛,所以我对发帖感觉有点不确定。

谁能告诉我下面的代码有什么问题。

所以我在错误中引用了一个函数。也就是说,如果发生错误,那么代码会重新引用它输入的函数再次运行。但是,当我第二次运行它时,我发现如果两个输入都是正确的(数字)输入,该函数不会返回值。

    #This is a program that is designed to calculate gross pay:

def main():
payment = input2()
print('Gross pay: $', format(payment, ',.2f'), sep='')

def input2():
try:
#we're first getting the number of hours that the user is working.

hours = int(input("How manyu hours did you work?: "))

pay_rate = int(input("Enter your hourly payrate here: "))

#display the gross pay
gross_pay = hours * pay_rate
payment = gross_pay
#display the gross pay:
except ValueError:
print('Error: Nope')
input2()
return payment

最佳答案

恕我直言,这不是递归的好用法,一个简单的 while 循环就可以了:

def input2():
while True:
try:
#we're first getting the number of hours that the user is working.
hours = int(input("How manyu hours did you work?: "))
pay_rate = int(input("Enter your hourly payrate here: "))

#display the gross pay
gross_pay = hours * pay_rate
return gross_pay
except ValueError:
print('Error: Nope')

修复你的递归调用看起来像:

def input2():
try:
#we're first getting the number of hours that the user is working.
hours = int(input("How manyu hours did you work?: "))
pay_rate = int(input("Enter your hourly payrate here: "))

#display the gross pay
gross_pay = hours * pay_rate
except ValueError:
print('Error: Nope')
gross_pay = input2()

return gross_pay

关于Python:错误处理递归函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50166612/

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