如何使random.choice()不再重新检查

时间:2016-01-16 01:38:47

标签: python function

今天我正在编写一个代码,它可以为你提供整数问题的加法或减法。例如:

from random import randint, choice
while True:
        value_1 = randint(-9,9)
        value_2 = randint(-9,9)
        lol = choice(['+', '-'])
        number = input("What is %s %s %s" % (value_1, lol, value_2))
        if lol == "+":
            try:
                number_x = int(number)
            except ValueError:
                 print("You did not enter a number silly goose")
            else:
                if number_x == value_1 + value_2:
                    print("You got the answer right. Good job!!")
                else:
                    print("Incorrecto my padwan. You still have much to learn")
        elif lol == "-":
            try:
                number_x = int(number)
            except ValueError:
                print("You did not enter a number silly goose")
            else:
                if number_x == value_1 - value_2:
                    print("You got the answer right. Good job!!")
                else:
                    print("Incorrecto my padwan. You still have much to learn")
        else:
            print("How did u even do this")

问题在于,当choice()函数选择“+”或“ - ”时,而不是在检查该人是否得到正确的答案时添加或减去我想要它,而是重新检查选择函数。这意味着,即使计算机询问此人“9 - 8是什么”,它也会重新检查lol。因此,计算机有时会检查该人是否得到9 + 8的正确答案,而不是检查该人是否得到9-8的答案。我想在这里做的是在第一次检查choice()函数之后,它保留输出,因此在计算机最初询问问题后它不会重新检查选择。或者是否有一种更简单的方式来写这个输出我要求的相同的东西?顺便说一句,抱歉这个问题写的很混乱,答案是否明显(我是编程新手)

1 个答案:

答案 0 :(得分:0)

我认为你可以尝试不同的方法。以下是我的参考:

import random

op1, op2 = ['', '-'], ['+', '-']
nums = list('0123456789')

if __name__ == '__main__':
    while True:
        question = ''.join([ random.choice(i) for i in (op1, nums, op2, nums) ])
        print 'Q: ' +  question + ' =',
        answer = raw_input()
        if answer == 'q':
            print 'Bye'
            break
        elif not answer.lstrip('-').isdigit():
            print '%s is not a valid answer\n' % (answer)
        elif int(answer) == eval(question):
            print 'Good Job\n'
        else: print 'Try again\n'

示例输出:

Q: -9+6 = 3
Try again

Q: 0-6 = -6
Good Job

Q: -3+3 = E
E is not a valid answer

Q: 1-2 = q
Bye