gpt4 book ai didi

Python 范围问题

转载 作者:太空宇宙 更新时间:2023-11-04 09:13:31 24 4
gpt4 key购买 nike

我正在编写一个程序,它需要确定数字的范围,就像我在 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

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

最佳答案

循环可以是:

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() 的作用。

关于Python 范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12226302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com