简体   繁体   中英

Random letter test in Python only works once every three times

The problem: I am writing a program that will test a players reflexes using a random letter (Q,W,E,R). The idea for the end program is that, when the player presses space, a timer will begin. Then the program will show them a random letter (Q,W,E,R). When they press the correct key and then press enter, it will print 'correct' and show them the next letter. If they press the wrong key, then press enter, the program will return 'incorrect'. After ten letters, it will divide their total time by ten to give them their reflex time. I have not added the timing part yet because of the problem, that it only prints 'Correct' or 'Incorrect' once every 3 times. The other times seem to be ignored and are not added to the score either. Thank you for helping me to fix this problem. When answering, please keep in mind that I am a new programmer so try and keep it as close to plain English as possible.

I am thinking it is something to do with me using/printing usertype more than once but I am not sure if that is the problem, and if it is how to fix it.

*EDIT I changed the code and used yours instead Martijn, it fixes my original problem, however, now I am receiving an indentation error on the "t" in result in result = usertype().

Output of the program: (my input in bold italics)

q

w

Incorrect

r

r

w

w

q

q

Correct

q

q

r

r

r

r

Correct

The code:

import random

def usertype(raw_input):
    randletter = random.choice('qwer')
    print randletter
    userinput = raw_input('')
    if userinput == randletter:
        return 'Correct'
    if userinput != randletter:
        return 'Incorrect'

def usertypetest(raw_input):
    x=0
    y=0
    while x <= 9:
        print usertype(raw_input)
        if usertype(raw_input) == 'Correct':
            x = x+1
            y = y+5
        if usertype(raw_input) == 'Incorrect':
            x = x+1
            y = y-2
    return y

print usertypetest(raw_input)

You are calling usertype() 3 times each loop iteration. Just call it once , store the result in a variable:

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

You don't need to use raw_input as a function argument anywhere here; just remove it from both the calls and the function parameter lists; usertype() is then:

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

and instead of testing for the inverse, just use else .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM