简体   繁体   English

如何在输入字符串后退出while循环

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

Trying to stop the below code from continuously requesting input after user enter q.尝试在用户输入 q 后阻止以下代码连续请求输入。 I enter q as the first input but loop just continues.我输入 q 作为第一个输入,但循环继续。 How do I get it while loop to stop if the user enter the letter q.如果用户输入字母 q,我如何让它 while 循环停止。 I'm using python3 Thank you.我正在使用 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:")

Check the input after they enter it, not when the loop repeats.在他们输入后检查输入,而不是在循环重复时检查。

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:")

Every time the loop has to run through all the way.每次循环都必须一直运行。 The only way to stop is to check during the loop if it q has been typed.停止的唯一方法是在循环期间检查是否已键入 q。 Eg:例如:

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

When you want to exit a loop, you can insert 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:")

Given the test your loop employs, you could also continue skipping to the next iteration.鉴于您的循环使用的测试,您还可以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