【发布时间】:2020-04-13 04:30:03
【问题描述】:
我正在编写一个程序,提示用户输入一些信息以输出支付金额。显示金额后,程序会询问用户是否要使用 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!')
【问题讨论】:
-
使用break语句
-
或在函数中使用 return
-
这能回答你的问题吗? Python Leave Loop Early
-
我已经尝试过使用 break,但仍然继续。
-
请添加一个普通的python标签
标签: python