-1

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

Community
  • 1
  • 1
WorkShoft
  • 440
  • 6
  • 18
  • try to never use global variables. – levi Jan 28 '15 at 16:46
  • there's not a lot of translation to do to apply this to your problem. every time you do `raw_input()` you're prompting the user for input. instead, store `raw_input` in a variable before your `if` and `elif`, then test the variable. – Zev Averbach Jan 28 '15 at 16:49
  • possible duplicate of [Why while loop is sticking at raw\_input? (python)](http://stackoverflow.com/questions/13267107/why-while-loop-is-sticking-at-raw-input-python) – Zev Averbach Jan 28 '15 at 16:51
  • in your code, inputing `d` requires inputing anything but `a` first, and then `d`. – njzk2 Jan 28 '15 at 16:56

2 Answers2

3

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
El Bert
  • 2,958
  • 1
  • 28
  • 36
0

Run this step by step:

  • raw_input is called, the user's input is read.
  • this input is compared to a.
  • if it is not a, raw_input is called again, the user's input is read.
  • this new input is compared to d.

As you can see, to input d, you must first not input a, as raw_input is called twice.

njzk2
  • 38,969
  • 7
  • 69
  • 107