在Python中使用if/else语句的While循环 [英] While loop with if/else statement in Python

查看:189
本文介绍了在Python中使用if/else语句的While循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我仍在学习Python,并且很难使用while循环.我下面有一个代码示例,其中包括while循环以及ifelse语句.我要它执行的操作是打印小于2"和大于4",但是它一直运行.它不会每次都打印一次,这是我希望它执行的操作.任何帮助将不胜感激!

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 

推荐答案

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

这将完成您想要的操作(如果少于2个,请打印此内容,等等)

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

这篇关于在Python中使用if/else语句的While循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆