我有一个任务是询问用户他们在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
Run Code Online (Sandbox Code Playgroud)
在这种情况下,不要使用单个变量,而是使用列表:
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)))
Run Code Online (Sandbox Code Playgroud)
如果你正在使用Python 3,你不需要调用str()上input()的结果.如果您使用的是Python 2,请raw_input()改用.
请注意,您不需要count变量,因为nod已经包含该信息.(你可以随时打电话len(directions)).请注意,第一个方向是direction[0]从Python算起0.