While loop with if/else statement in Python

偶尔善良 提交于 2019-12-12 04:10:00

问题


So I am still in the process of learning Python and I am having difficultly with while loops. I have a sample of code below that includes while loop and if and else statements. 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!

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 

回答1:


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:


I'm assuming you want to say Less than 2 or Greater than 4 while incrementing from 1 to 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 4 because your while condition is counter < 5.



来源:https://stackoverflow.com/questions/36843103/while-loop-with-if-else-statement-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!