1

我正在编写一个程序,它需要确定数字的范围,就好像我将 15 放在 user_input 'a' 中,所以它应该打印从 '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

或者

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

1 回答 1

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)是一个列表(在 Python 2 中),从ab-1(不包括在内),按-1. 例如,您可以尝试在 Python shell 中执行此操作print range(10, 5, -1)。您还可以检查 , 的输出range(5, 11, 2)以更好地了解range()它的作用。
于 2012-09-01T08:48:35.463 回答