簡體   English   中英

如何在輸入字符串后退出while循環

[英]How to quit while loop after a string input

嘗試在用戶輸入 q 后阻止以下代碼連續請求輸入。 我輸入 q 作為第一個輸入,但循環繼續。 如果用戶輸入字母 q,我如何讓它 while 循環停止。 我正在使用 python3 謝謝。

w = ''
while w != 'q':
    w = input("Enter the student's W#:")
    name = input("Enter the student's name:")
    phone = input("Enter the students phone number:")

在他們輸入后檢查輸入,而不是在循環重復時檢查。

while True:
    w = input("Enter the student's W# or q to end:")
    if w == 'q':
        break
    name = input("Enter the student's name:")
    phone = input("Enter the student's phone number:")

每次循環都必須一直運行。 停止的唯一方法是在循環期間檢查是否已鍵入 q。 例如:

while true:
    w = input("Enter the student's W#:")
    if (w == 'q') 
        break
    name = input("Enter the student's name:")
    if (name == 'q') 
        break
    phone = input("Enter the students phone number:")
    if (phone == 'q') 
        break

當你想退出一個循環時,你可以插入break

w = ''
while w != 'q':
    w = input("Enter the student's W#:")
    if w == 'q': break
    name = input("Enter the student's name:")
    phone = input("Enter the students phone number:")

鑒於您的循環使用的測試,您還可以continue跳到下一次迭代。

w = ''
while w != 'q':
    w = input("Enter the student's W#:")
    if w == 'q': continue
    name = input("Enter the student's name:")
    phone = input("Enter the students phone number:")

暫無
暫無

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

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