所以我仍然在学习Python,我很难使用while
循环。我在下面有一些代码示例,其中包含while
循环以及if
和else
语句。我想要它做的是打印'小于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
答案 0 :(得分:5)
counter = 1
while (counter <= 5):
if counter < 2:
print("Less than 2")
elif counter > 4:
print("Greater than 4")
counter += 1
这将做你想要的(如果少于2,打印此等)
答案 1 :(得分:1)
我假设您想要在从1增加到4时说Less than 2
或Greater than 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
该程序永远不会显示Greater than 4
,因为您的while条件为counter < 5
。
答案 2 :(得分:0)