这是我的第一篇文章,我对python和整个编程还相当陌生。如果我问了一些愚蠢的问题或格式不正确,我深表歉意。
我目前正在编程一个finch机器人来读取用户输入列表,然后根据用户输入顺序运行。我已经编写了导致for循环的代码,但是我不知道从这里开始该做什么。
>userInputList = []
loop = False
while loop == False :
#Instructions for what to type
print("W - Move Forward")
print("S - Move Backward")
print("A - Turn Left")
print("D - Turn Right")
print("X - Execute Commands")
print("Q - Quit")
userInput = str(input("Please enter a command for the Finch: "))
if userInput.upper() in ["Q"] :
print("Quitting")
finch.close
loop = True
elif userInput.upper() in ["X"] :
loop = True
print("Executing")
else :
userInputList.append(userInput)
userTime = float(input("Please enter the duration in seconds: "))
userInputList.append(userTime)
if userInput.upper() in ["W"] :
print("Moving forward for " +str(userTime), "seconds")
elif userInput.upper() in ["S"] :
print("Moving backward for " +str(userTime), "seconds")
elif userInput.upper() in ["A"] :
print("Turning left for " +str(userTime), "seconds")
elif userInput.upper() in ["D"] :
print("Turning right for " +str(userTime), "seconds")
else :
print("")
以上是我迄今为止的代码,它似乎工作正常。下面是我感到困惑的for循环代码。如果我一起访问这对用户输入,效果会更好吗?或者,如果我先读取str值,然后再读取float值?我想我会通过以2为增量阅读列表来完成后者。
>for userInputList in range(0, len(userInputList), 2) :
if userInputList in ["W", "w"] :
print("Working") #Used to determine if the loop is working correctly, will be deleted later on
你有什么理由想把方向和时间放在一个单一的平面列表中吗?把它们分开可能更容易。
假设你有一个方向序列:
directions = ["W", "S", "W"]
以及相应的时间序列:
times = [0.5, 0.1, 0.2]
你可以这样循环它们:
for direction, time in zip(directions, times):
print(direction, time)
#do something with them, move your robot, etc
如果你不想把它们分开,你可以把它们成对地添加到列表中,比如:
move_list.append((userInput, userTime))
然后像这样循环通过它们:
for direction, time in move_list:
print(direction, time)
这回答了你的主要问题吗?
作为一个提示,你可能也会考虑,只要你得到这样的结果,就把方向输入的结果变成大写:
userInput = str(input("Please enter a command for the Finch: ")).upper()
这样,您就不必每次检查其值时都将其设为大写。