Python 如何更改正在使用的变量?
我有一个任务要问用户,对于python中的Finch机器人,他们有多少个方向。 在我知道有多少个方向后,我需要询问并保存其中的每一个。 我不知道的是如何切换我使用的变量,并且仍然存储用户的答案Python 如何更改正在使用的变量?,python,variables,Python,Variables,我有一个任务要问用户,对于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 " +
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)))
如果您使用的是Python3,则不需要对input()
的结果调用str()
。如果您使用的是Python 2,请改用raw\u input()
请注意,您不需要
count
变量,因为nod
已经包含该信息。(以后您可以随时拨打len(方向)
)。请注意,第一个方向是方向[0]
,因为Python从0
开始计数使用列表而不是单个变量。您使用的是Python 3吗?