2012-09-01 181 views
1

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

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 

回答

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循环为你做递减(无需i = i-1像C)。
  2. range(a, b-1, -1)是从ab-1(未包括)的列表(在Python 2中),步骤为-1。例如,您可以尝试在Python shell中执行print range(10, 5, -1)。您还可以检查range(5, 11, 2)的输出,以更好地了解range()的功能。
+0

nah bro它没有:/ – rocker789

+0

@ rocker789:现在确实如此。你的循环正在向上计数(两次)。 –

+0

该范围内应该是b + 1吗? –