簡體   English   中英

如何在python中退出while循環?

[英]How to exit a while loop in python?

我正在做這個簡單的任務,我需要使用2個while循環。 第一個while循環檢查小時數是否小於0,如果是,則循環應該繼續詢問用戶。 這是我的代碼:

hours = float(input('Enter the hours worked this week: '))

count = 0
while (0 > hours):
    print ('Enter the hours worked this week: ')
    count = count + 1

pay = float(input('Enter the hourly pay rate: '))
while (0 > pay):
    print ('Enter the hourly pay rate: ')
    count = count + 1

total_pay = hours * pay

print('Total pay: $', format(total_pay, ',.2f'))

break是你正在尋找的。

x = 100
while(True):
    if x <= 0:
        break
    x -= 1
print x # => 0

至於你的例子,似乎沒有任何東西會導致中斷發生。 例如:

hours = float(input('Enter the hours worked this week: '))

count = 0

while (0 > hours):
    print ('Enter the hours worked this week: ')
    count = count + 1

您根本沒有編輯hours變量。 這只會繼續打印出"Enter the hours worked this week: "和無限增量count 我們需要知道提供更多幫助的目標是什么。

您可以通過使用break或使條件為false來退出循環。

在您的情況下,您從用戶處獲取輸入,如果hours < 0 ,則打印提示並更新計數,但不會更新小時數。

while (0 > hours):
    print ('Enter the hours worked this week: ')
    count = count + 1

應該:

while (0 > hours):
    hours = float(input('Enter the hours worked this week: '))
    count = count + 1

同樣的薪酬:

while (0 > pay):
    pay = float(input('Enter the hourly pay rate: '))
    count = count + 1

好吧,另一個答案向您展示了如何突破while循環,但您也沒有分配付費和小時變量。 您可以使用內置輸入功能來獲取用戶提供給程序的內容

hours = float(input('Enter the hours worked this week: '))

count = 0
while (0 > hours):
    hours = input('Enter the hours worked this week: ')
    count = count + 1

pay = float(input('Enter the hourly pay rate: '))
while (0 > pay):
    pay =  input('Enter the hourly pay rate: ')
    count = count + 1

total_pay = hours * pay

print('Total pay: $', format(total_pay, ',.2f'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM