Python向上和向下循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33401542/
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 13:18:09  来源:igfitidea点击:

Python Count up & Down loop

pythonloopscountercountdown

提问by NoCash4College

How can I simply transform this loop to count up from 1 to 100, and display the numbers? I'm starting to code recently. It works fine when counting down, but I can't figure out how to make it go from 1 -100

我怎样才能简单地转换这个循环从 1 到 100 计数,并显示数字?我最近开始编码。倒计时时效果很好,但我不知道如何让它从 1 -100 开始

example:

例子:

count = 100
while count > 0 :
    print(count)
    count = count - 1

采纳答案by Shawn Mehan

Start at 1, and change your conditional to break out when you reach 100. Add 1 each loop through.

从 1 开始,当你达到 100 时改变你的条件来突破。每次循环加 1。

count = 1
while count <= 100:
    print(count)
    count += 1

回答by Tofystedeth

Basically just do the opposite of what you've already got.

基本上只是做与你已经得到的相反的事情。

count = 1
while count < 101:
    print(count)
    count = count + 1

回答by F. Guinn

just start your count at 1, change your check statement to check if the number is less than 100, and use "count = count + 1" Should work, good luck!

只需从 1 开始计数,更改检查语句以检查数字是否小于 100,并使用 "count = count + 1" 应该可以工作,祝你好运!

回答by Nathan Ansel

If you use a for loop it gets really easy:

如果您使用 for 循环,它会变得非常简单:

for number in range(1,101):
    print(number)

And for going from 100 down to 1:

从 100 降到 1:

for number in range(100,0,-1):
    print(number)

回答by user1519166

Can try 'reversed':

可以尝试“反转”:

>>> for i in reversed(range(1,11)):
...   print i
... 
10
9
8
7
6
5
4
3
2
1

回答by Etherhead

Try this.

尝试这个。

count = 0
 while count <= 100:
        print ("Count = ", count)
        count = count + 1