这是我的第三个问题。我现在已经两次在堆栈溢出的情况下被投票离开了岛屿,所以我对发帖感到有些不确定。
有人可以告诉我以下代码有什么问题。
所以我在错误中引用了一个函数。也就是说,如果发生错误,则代码重新引用它输入的函数,它再次运行。但是,当我第二次运行它时,如果两个输入都是正确的(数字)输入,我发现函数没有返回值。
#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
答案 0 :(得分:1)
恕我直言,这不是一个很好的递归使用,一个简单的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
答案 1 :(得分:0)
根据您的缩进,该函数仅返回Except块中的任何内容。如果您在没有错误的情况下通过了所有尝试的内容,那么您将永远无法获得“退款”。
希望有所帮助。
答案 2 :(得分:-1)
修正了你的代码,你走了,
def main():
payment = input2()
print('Gross pay: $', format(payment), 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
#display the gross pay
return gross_pay
except ValueError
print('Error: Nope')
return input2()
main()