为什么随机输出错误

时间:2019-11-18 17:12:27

标签: python random

我写了一个数学游戏程序,可以根据正确答案计算分数。它将询问用户两次给定问题的答案,如果答案正确,它将增加10。但是分数未正确添加,我不知道为什么。

import random
def game():
    l = ['*','+']
    score = 0
    for _ in range(2):
        x = random.randint(1,5)
        y = random.randint(1,5)
        z = int(input("Enter the val of {} {} {} \n".format(x, random.choice(l), y)))
        if random.choice(l) == '*':
            o = x * y
        elif random.choice(l) == '+':
            o = x + y
        if z == o:
            score = score + 10
            print(score)
    return("Your score is {}".format(score))

game()

1 个答案:

答案 0 :(得分:4)

您需要记住您的选择。每次您致电random.choice(l)时,都会选择一个新电话:

import random
def game():
    l = ['*','+']
    score = 0
    for _ in range(2):
        choice = random.choice(l)
        x = random.randint(1, 5)
        y = random.randint(1, 5)
        z = int(input("Enter the val of {} {} {} \n".format(x, choice, y)))

        if choice == '*': # Here you chose something random
            o = x * y
        elif choice == '+': # and here you chose something random
            o = x + y
        if z == o:
            score = score + 10
            print(score)
    return("Your score is {}".format(score))

print(game())

还有一些建议:

1)我建议使用f字符串,它看起来更好:

z = int(input(f"Enter the val of {x} {choice} {y} \n".))

2)使用更有意义的变量名称代替xyzo

最后一个高级技巧。如果您想使这款游戏更加通用,可以使用operator模块。然后,您可以轻松添加更多操作。

import random
import operator

def game():
    operators = {
      '*': operator.mul,
      '+': operator.add,
      '-': operator.sub,
    }
    score = 0
    for _ in range(2):
        choice = random.choice(list(operators.keys()))
        x = random.randint(1, 5)
        y = random.randint(1, 5)
        user_answer = int(input(f"Enter the val of {x} {choice} {y} \n"))
        actual_answer = operators[choice](x, y)
        if user_answer == actual_answer:
            score = score + 10

    return("Your score is {}".format(score))

print(game())