Python范围问题

时间:2012-09-01 08:45:51

标签: python while-loop range

我正在编写一个程序,在这个程序中需要确定数字的范围,就像我在user_input'a'中放入15一样,所以它应该打印范围从'a'到'b'但不幸的是我无法工作任何人都可以帮助我这个。这是我的代码:

a = int(raw_input("How many did you say you're going to count down? "))
b = int(raw_input("When are you actually going to stop? "))
i = 0
for i in range(a, b):
    i = i + 1
    print i 

我希望它能像这样工作:

How many did you say you're going to count down? 15
When are you actually going to stop? 8
15
14
13
12
11
10
9
8

OR

How many did you say you're going to count down? 6
When are you actually going to stop? 4
6
5
4

1 个答案:

答案 0 :(得分:5)

循环可以是:

a = int(raw_input("How many did you say you're going to count down? "))
b = int(raw_input("When are you actually going to stop? "))

for i in range(a, b-1, -1):
    print i 

(假设计数减少)。

你必须知道的是:

  1. for循环为您做了减量(C中不需要i = i-1)。
  2. range(a, b-1, -1)是一个列表(在Python 2中),从ab-1(未包含),步长为-1。例如,您可以在Python shell中尝试print range(10, 5, -1)。您还可以查看range(5, 11, 2)的输出,以更好地了解range()的作用。