Skip to main content
 首页 » 编程设计

Python之心算测试(这能更有效吗)

2024年10月24日17mfrbuaa

我一直在努力提高我的 Python 技能,基本上我决定制作这个程序,它只使用 +、- 和/向用户询问 10 个简单的数学问题。我的代码有效(好吧,我已经对其进行了测试,到目前为止它确实有效)但我希望它保留其当前功能。但是有没有一种方法可以提高效率呢?这是 Python 3.4.3

    import random 
 
    username = input("Enter your name: ") 
    score = 0 
 
    for i in range(10): 
        sign = "" 
        answer = 0 
        numOne = random.randint(1,10) 
        numTwo = random.randint(1,10) 
        pickOperator = random.randint(1,3) 
        if pickOperator == 1: 
            sign = " + " 
            answer = numOne + numTwo 
        elif pickOperator == 2: 
            sign = " - " 
            answer = numOne - numTwo 
       elif pickOperator == 3: 
            sign = " * " 
            answer = numOne * numTwo 
        else: 
            print ("An error has occured") 
        question = "What is " + str(numOne) + sign + str(numTwo) + "? " 
        user_answer = int(input(question)) 
        if user_answer == answer: 
            print ("That was the correct answer!") 
            score = score + 1 
        else: 
            print ("That answer was incorrect!") 
 
    print (username + " you got " + str(score) + " out of 10") 

请您参考如下方法:

可以做几件事来让你的代码更像 Pythonic,但请注意:效率(比如运行代码更快)可能是一样的,因为它的速度可能会受到用户输入数据的速度的限制,这是比您的计算机时钟慢几个数量级。

为了便于扩展您的操作,您可以创建如下内容:

from operator import add, sub, mul 
signs = ['+', '-', '*'] 
operations = [add, sub, mul] 
mapping = {s: o for s, o in zip(signs, operations)} 

因此,您可以这样使用您的pickOperator:

sign = signs[pickOperator] 
operation = mapping[sign] 
answer = operation(numOne, numTwo) 

并删除所有那些if、elif。

当一个无效操作发生时,你的sign赋值你将收到一个异常(IndexError)。所以你必须捕获它并显示你的错误信息来继续程序。尽管如果您正确使用随机函数,这种情况永远不会发生:

考虑使用 randrange 而不是 randint。所以你将能够写:

pickOperator = random.randrange(0, len(signs)) 

另一种选择是放弃这个变量并使用 random.choice 代替:

sign = random.choice(signs)