Search code examples
pythonstringrandominputraw-input

Program stuck in while loop not printing


import random

def usertype():
    randletter = random.choice('qwer')
    userinput = raw_input('Press '+str(randletter))
    if userinput == randletter:
        return 'Correct'
    else:
        return 'Incorrect'

def usertypetest(x,y,result):
    while x <= 9:
        result = usertype()
    if result == 'Correct':
        x = x+1
        y = y+5
    else:
        x = x+1
        y = y-2
    return str(y)+'is your score'

print usertypetest(0,0,usertype)

Here is my code. I want it to ask the user to press a button, randomly chosen from the set (Q, W, E, R), then print either correct or incorrect, depending on which button they press. I want this to happen 10 times. After ten tries it will print their score: 5 for each 'Correct' and -2 for 'Incorrect'. Instead I receive this.

Press e(e)
Press e(e)
Press w(e)
Press q(e)
Press q(e)
Press q(e)
Press r(e)
Press e(e)
Press w(e)
Press q(e)
Press e(e)
Press e(e)
Press e(e)
Press e(e)
Press q(e)
Press w(e)
Press r(e)
Press w(e)
Press r(e)
Press w(e)
Press r(e)
Press r(e)

Regardless of what I enter, it returns neither 'Correct', nor 'Incorrect'. It also continues on past 10 and does not show their score. There is clearly a problem I am not seeing.

My input is in brackets.

For clarification, this is what I want:

Press q(q)
Correct
Press e(q)
Incorrect
Press w(w)
Correct
Press q(q)
Correct
Press e(eq)
Incorrect
Press e(e)
Correct
Press q(q)
Correct
Press q(r)
Incorrect
Press w(w)
Correct
Press r(r)
Correct
29 is your score

Solution

  • In Python indentation is very important.

    In this code, the x for the while loop is never changed as the if block is on the same indent level as the while loop. So the only looped instruction is result = usertype()

    while x <= 9:
        result = usertype()
    if result == 'Correct':
        x = x+1
        y = y+5
    

    Two additional critiques:

    You are incrementing x in two places, when it only needs to be done once.

    while x <= 9:
        result = usertype()
        if result == 'Correct':
            y = y+5
        else:
            y = y-2
        x += 1
    

    Also, since you are looping a fixed number of times, why not ignore incrementing x and use a for loop, like so:

    for x in range(10):
        result = usertype()
        if result == 'Correct':
            y = y+5
        else:
            y = y-2