[英]How do I exit a while loop?
我正在編寫一個程序,提示用戶輸入一些信息到 output 支付金額。 顯示金額后,程序會詢問用戶是否要使用 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!')
您已經嵌套了 while 循環。 你需要擺脫他們兩個。
我認為你的問題是,每次計算后它都會問你問題“'你想要另一個薪酬計算嗎?(y或n)'”,如果你回答n,仍然執行在循環內。
您在 while 中使用以下條件
while repeat == 'y' or 'Y': #this is wrong
當您編寫上述條件時,它實際上解析為
while (repeat == 'y') or ('Y'):
這里第一個條件為假,但第二個條件為真。 所以執行將在 go 里面。
而是使用下面的“in”關鍵字。
while repeat in ['y', 'Y']: #I will prefer this.
或者
while repeat == 'y' or repeat=='Y':
或者
while repeat == ('y' or 'Y'):
希望這會幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.