我正在编写一个程序,提示用户输入一些信息以输出支付金额。显示金额后,程序会使用while循环询问用户是否要重复。在定义了计算支付金额的程序之后,有一个while循环重复输入的问题。问题是我找不到退出循环的方法。 这是我到目前为止的内容:
def CalPay(hrs,rate):
print('Please enter number of hours worked for this week:', hrs)
print('What is hourly rate?', rate)
try:
hrs = float(hrs)
except:
print('You entered wrong information for hours.')
return
try:
rate=float(rate)
except:
print('You entered wrong rate information.')
return
if hrs < 0:
print('You entered wrong information for hours.')
elif rate < 0:
print('You entered wrong rate information.')
else:
if hrs > 60:
pay=((hrs-60)*2*rate)+(20*rate*1.5)+(rate*40)
print('Your pay for this week is:', '$'+str(pay))
elif hrs > 40:
pay=((hrs-40)*1.5*rate)+(rate*40)
print('Your pay for this week is:', '$'+str(pay))
else:
pay=rate*hrs
print('Your pay for this week is:', '$'+str(pay))
repeat=input('Do you want another pay calculation?(y or n)')
while repeat == 'y' or 'Y':
while True:
try:
hrs = float(input('Please enter number of hours worked for this week:'))
except:
print('You entered wrong information for hours.')
continue
else:
break
while True:
try:
rate=float(input('What is hourly rate?'))
except:
print('You entered wrong rate information.')
continue
else:
break
if hrs < 0:
print('You entered wrong information for hours.')
elif rate < 0:
print('You entered wrong rate information.')
else:
if hrs > 60:
pay=((hrs-60)*2*rate)+(20*rate*1.5)+(rate*40)
print('Your pay for this week is:', '$'+str(pay))
elif hrs > 40:
pay=((hrs-40)*1.5*rate)+(rate*40)
print('Your pay for this week is:', '$'+str(pay))
else:
pay=rate*hrs
print('Your pay for this week is:', '$'+str(pay))
repeat=input('Do you want another pay calculation?(y or n)')
print('Good Bye!')
答案 0 :(得分:0)
您嵌套了while循环。您需要打破两者。
答案 1 :(得分:0)
我认为您的问题是,每次计算后,它都会问您“是否要进行另一次工资计算(是y或n)”,并且如果您回答n,执行仍在循环内进行。
您正在使用以下条件
while repeat == 'y' or 'Y': #this is wrong
在您写上述条件时,它实际上会解析为
while (repeat == 'y') or ('Y'):
此处第一个条件为假,而第二个条件为真。因此执行将在一段时间内完成。
请使用“ in”关键字,如下所示。
while repeat in ['y', 'Y']: #I will prefer this.
或
while repeat == 'y' or repeat=='Y':
或
while repeat == ('y' or 'Y'):
希望这会对您有所帮助。