繁体   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