在 Python 中使用 if/else 语句进行 while 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36843103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:26:00  来源:igfitidea点击:

While loop with if/else statement in Python

pythonif-statementwhile-loop

提问by A.LeBrun

So I am still in the process of learning Python and I am having difficultly with whileloops. I have a sample of code below that includes whileloop and ifand elsestatements. What I want it to do is print 'Less than 2' and 'Greater than 4' which it does, but it keeps running. It does not print it just once each which is what I would want it to do. Any help would be greatly appreciated!

所以我仍然在学习 Python 的过程中,我很难使用while循环。我有下面的代码示例,其中包括while循环和ifelse语句。我想让它做的是打印“小于 2”和“大于 4”,但它会继续运行。它不会每次只打印一次,这是我希望它做的。任何帮助将不胜感激!

counter = 1
while (counter < 5):
    count = counter
    if count < 2:
        counter = counter + 1
    else:
        print('Less than 2')
    if count > 4:
        counter = counter + 1
    else:
        print('Greater than 4')
    counter = counter + 1 

回答by trolley813

counter = 1 
while (counter <= 5): 
    if counter < 2:
        print("Less than 2")
    elif counter > 4:
        print("Greater than 4")
    counter += 1

This will do what you want (if less than 2, print this etc.)

这会做你想要的(如果少于 2,打印这个等等)

回答by Scratch'N'Purr

I'm assuming you want to say Less than 2or Greater than 4while incrementing from 1 to 4:

我假设您想说Less than 2Greater than 4从 1 增加到 4:

counter = 1
while (counter < 5):
    if counter < 2:
        print('Less than 2')
    elif counter > 4:
        print('Greater than 4')
    else:
        print('Something else') # You can use 'pass' if you don't want to print anything here
    counter += 1

The program will never display Greater than 4because your while condition is counter < 5.

该程序将永远不会显示,Greater than 4因为您的 while 条件是counter < 5.