gpt4 book ai didi

python - 如何更改正在使用的变量?

转载 作者:行者123 更新时间:2023-11-28 21:19:20 25 4
gpt4 key购买 nike

我有一个任务是用 Python 询问用户他们对 Finch 机器人有多少方向。在我知道有多少方向之后,我需要询问并保存每一个方向。我想不通的是如何切换我正在使用的变量并仍然存储用户的答案。

count = 1

nod = int(input("How many directions do you have?: ")) #nod = number of directions
for int in range(0, nod):
d1 = str(input("Direction " + str(count) + ": "))
#I want to switch out d1 with d2,d3, etc. for as many directions as the user has
count += 1

最佳答案

在这种情况下,不要使用单个变量,而是使用列表:

directions = []
nod = int(input("How many directions do you have?: ")) #nod = number of directions
for i in range(nod):
directions.append(input("Direction {}: ".format(i+1)))

如果您使用的是 Python 3,则无需对 input() 的结果调用 str()。如果您使用的是 Python 2,请改用 raw_input()

请注意,您不需要 count 变量,因为 nod 已经包含该信息。 (而且您始终可以稍后调用 len(directions))。请注意,第一个方向是 direction[0],因为 Python 从 0 开始计数。

关于python - 如何更改正在使用的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24813072/

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