【问题标题】:Python: how to make python calculate a sum to make sure an input is correct?Python:如何让 python 计算总和以确保输入正确?
【发布时间】:2016-07-16 17:50:39
【问题描述】:

我想让 python 问 10 个问题,并且用户必须输入他们的答案,这很有效。但是,我也希望 python 通过使用下面的代码来说明这是否正确,但这不起作用,只能转到下一个问题。谁能告诉我为什么?或者我需要改变什么?另外,如何使用我拥有的变量和 while 循环专门提出 10 个问题?

import time
import random
question = 0
score = 0
name = input("What is your full name?")
print ("Hello " + name, "welcome to The Arithmetic Quiz")
time.sleep(2)
operand1 = list(range(2, 12))
operators = ["+"]
operand2 = list(range(2, 12))

while question < 10:
    user_answer=int(input(str(random.choice(operand1)) + random.choice(operators) + str(random.choice(operand2))))
    if operators=='+':
        expected_answer==operand1 + operand2
        if user_answer==expected_answer:
            print('This is correct!')
            score = score + 1
            question = question + 1
            time.sleep(2)
        else:
            print('This is incorrect!')
            question = question + 1
            time.sleep(2)

【问题讨论】:

  • 我假设基于 input 的使用方式,这是 Python 3?

标签: python loops variables while-loop sum


【解决方案1】:

您在while 语句中的所有比较都是针对lists 而不是随机选择的元素进行的。

你可能想做这样的事情:

operands1 = list(range(2, 12))
operators = ["+"]
operands2 = list(range(2, 12))

while question < 10:
    operand1 = random.choice(operands1)
    operand2 = random.choice(operands2)
    operator = random.choice(operators)
    user_answer = int(input('{} {} {} '.format(operand1, operator, operand2)))
    if operator == '+':
        expected_answer = operand1 + operand2
        if user_answer == expected_answer:
            print('This is correct!')
            score = score + 1
            question = question + 1
            time.sleep(2)
        else:
            print('This is incorrect!')
            question = question + 1
            time.sleep(2)

还有很多其他的方法可以改进代码的结构,这可能会让它看起来像这样:

import operator as ops
import time
import random

NUM_QUESTIONS = 10
OPERANDS = list(range(2, 12))
OPERATORS = {'+': ops.add, '-': ops.sub, '*': ops.mul}

def getInteger(prompt, errormsg='Please input an integer'):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print(errormsg)

def main():
    question = score = 0

    name = input('What is your full name? ')
    print('Hello {}, welcome to The Arithmetic Quiz'.format(name))
    time.sleep(2)

    for _ in range(NUM_QUESTIONS):
        operand1 = random.choice(OPERANDS)
        operand2 = random.choice(OPERANDS)
        operator = random.choice(list(OPERATORS))

        user_answer = getInteger('{} {} {} '.format(operand1, operator, operand2))
        expected_answer = OPERATORS[operator](operand1, operand2)
        if user_answer == expected_answer:
            print('This is correct!')
            score += 1
        else:
            print('This is incorrect!')
        time.sleep(2)

if __name__ == '__main__':
    main()

这使用专用的getInteger 函数来处理无效输入,使用字典和函数作为一流的对象来选择要使用的“实际”运算符函数,使用+=,使用rangefor ,而不是 while 循环,使用合理的常量...可能的改进列表很大。

【讨论】:

  • 对我来说,冒号对于 if operator == '+' 来说是无效的语法:
  • @Ikr 现在都修好了。
【解决方案2】:

这是代码的问题

import time
import random
question = 0
score = 0
name = input("What is your full name?")
print ("Hello " + name, "welcome to The Arithmetic Quiz")
time.sleep(2)
operand1 = list(range(2, 12))
#Choice works fine with ranges 
#No need to transform it with a list
operators = ["+"]
operand2 = list(range(2, 12))
#Using the for loop is more Pythonic
while question < 10: 
    user_answer=int(input(str(random.choice(operand1)) + random.choice(operators) + str(random.choice(operand2))))
    if operators=='+': ##Over here you were comparing a list to a str
        expected_answer==operand1 + operand2 ##This is a boolean operator not an int value
        if user_answer==expected_answer:
            print('This is correct!')
            score = score + 1
            question = question + 1
            time.sleep(2)
        else:
            print('This is incorrect!')
            question = question + 1
            time.sleep(2)

正如 Kupiakos 所说,优化代码的方法有很多,他已经介绍了其中的大部分。我会指出解决上述问题的方法。

import time
from random import choice, randint
question, score = 0, 0

name = input("What is your full name?\n>>> ")
print ("Hello {} welcome to The Arithmetic Quiz\n".format(name))
time.sleep(2)

for _ in range(10):
    operand1, operand2 = [randint(2, 12) for _ in range(2)]
    op = choice(['+'])##You have to store the value so that you can compare it later
    user_answer=int(input('{0}{2}{1}\n>>> '.format(operand1, operand2, op) ))
    if op == '+':
        expected_answer = operand1 + operand2
        if user_answer == expected_answer:
            print('This is correct!')
            score += 1
            question += 1
            time.sleep(2)
        else:
            print('This is incorrect!')
            question = question + 1
            time.sleep(2)
print('Your score is: {} points'.format(score))

祝你的学生好运。

【讨论】:

  • ##Over 在这里您将列表与 str 进行比较是什么意思?
  • 另外,我将如何更改 expected_answer==operand1 + operand2?
  • ['+'] 属于列表类,而当您从中选择一个随机元素时,该元素是一个str。您的条件是 '['+']=='+' ,因为它们属于不同的类,所以它总是会返回 false。如果你对它们都使用'type()',你会明白我的意思。 @lkr
  • == 返回一个布尔运算符(True 或 False)将为 (=) 分配一个值。所以你必须说 expected_answer = .. not == 因为后者会产生一个(真或假)。
  • 如果 operator=='+' 改为,你会改变什么?
【解决方案3】:

以下是您的问题的解决方案:

import time
import random

question = 0
score = 0
name = input("What is your full name?")
print ("Hello " + name, "welcome to The Arithmetic Quiz")
time.sleep(2)
operand1 = list(range(2, 12))
operand2 = list(range(2, 12))

while question < 10:
    num1 = random.choice(operand1)
    num2 = random.choice(operand2)
    print(str(num1) + "+" + str(num2))
    user_answer = int(input())
    expected_answer = int(num1) + int(num2)
    if user_answer == expected_answer:
        print('This is correct!!')
        score = score + 1
        question = question + 1
    else:
        print('This is incorrect!!')
        question = question + 1

print("\nYour score is " + str(score))

这里不需要操作数变量,而是可以将 + 运算符作为字符串本身传递。 此外,expected_answer 变量无法解析求和,因为操作数 1 和操作数 2 作为列表而不是 int 传递。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 2015-04-14
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    相关资源
    最近更新 更多