Python: raw_input 第一次要求输入一次,然后两次
Python: raw_input asks for input once the first time, then twice
我 运行 在我的电脑上查看这段旧代码:
# -*- coding: utf-8 -*-
player_pos = 2
def game():
global player_pos
background = [2, 1, 2, 1, 2]
screen = [0] * 5
for i in range(5):
screen[i] = background[i]
screen[player_pos] = 7
print screen
if raw_input("> ") == 'a':
player_pos -= 1
elif raw_input("> ") == 'd':
player_pos += 1
while True:
game()
我从 IDLE 运行 它,提示按预期工作。但是,如果你按'a'或'd',它可能会正常工作或只打印一个空行,然后再按'd'就可以正常工作。
所以你需要按一次或两次'a'或'd',我希望它总是一次。
我发现了这个问题,但我不知道如何将其转化为我的问题。运行 Simple:Python asks for input twice
您正在调用 raw_input
方法两次 - 每个 if
语句一次。
您可以将用户输入存储在本地变量中,然后对其进行测试:
user_answer = raw_input("> ")
if user_answer == 'a':
player_pos -= 1
elif user_answer == 'd':
player_pos += 1
运行这一步一步:
raw_input
被调用,用户输入被读取。
- 将此输入与
a
进行比较。
- 如果不是
a
,则再次调用raw_input
,读取用户的输入。
- 将此新输入与
d
进行比较。
如您所见,要输入d,您必须先不输入a,因为raw_input
被调用了两次。
我 运行 在我的电脑上查看这段旧代码:
# -*- coding: utf-8 -*-
player_pos = 2
def game():
global player_pos
background = [2, 1, 2, 1, 2]
screen = [0] * 5
for i in range(5):
screen[i] = background[i]
screen[player_pos] = 7
print screen
if raw_input("> ") == 'a':
player_pos -= 1
elif raw_input("> ") == 'd':
player_pos += 1
while True:
game()
我从 IDLE 运行 它,提示按预期工作。但是,如果你按'a'或'd',它可能会正常工作或只打印一个空行,然后再按'd'就可以正常工作。 所以你需要按一次或两次'a'或'd',我希望它总是一次。
我发现了这个问题,但我不知道如何将其转化为我的问题。运行 Simple:Python asks for input twice
您正在调用 raw_input
方法两次 - 每个 if
语句一次。
您可以将用户输入存储在本地变量中,然后对其进行测试:
user_answer = raw_input("> ")
if user_answer == 'a':
player_pos -= 1
elif user_answer == 'd':
player_pos += 1
运行这一步一步:
raw_input
被调用,用户输入被读取。- 将此输入与
a
进行比较。 - 如果不是
a
,则再次调用raw_input
,读取用户的输入。 - 将此新输入与
d
进行比较。
如您所见,要输入d,您必须先不输入a,因为raw_input
被调用了两次。