Search code examples
pythonpython-idle

Python: raw_input asks for input once the first time, then twice


I ran across this old piece of code on my PC:

# -*- 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()

I run it from IDLE and the prompt works as expected. However, if you press 'a' or 'd', it may work properly or just print a blank line, and then work properly if you press 'd' again. So you need to press 'a' or 'd' once or twice, and I want it to always be once.

I found this question but I don't know how to translate it to my problem. Simple:Python asks for input twice


Solution

  • You are calling the raw_input method twice - once in each if statement. You could store the user input in a local var and then test it:

    user_answer = raw_input("> ")
    if user_answer == 'a':
        player_pos -= 1
    elif user_answer == 'd':
        player_pos += 1