簡體   English   中英

Python:如何使python計算總和以確保輸入正確?

[英]Python: how to make python calculate a sum to make sure an input is correct?

我想讓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)

while語句中的所有比較都是針對list而不是針對隨機選擇的元素進行的。

您可能想要執行以下操作:

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循環,使用合理的常量...可能的改進清單很大。

這是代碼的錯誤

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))

祝你學生好運。

以下是您的問題的解決方案:

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))

這里不需要操作數變量,而是可以將+運算符本身作為字符串傳遞。 另外,由於將操作數1和操作數2作為列表而不是整數進行傳遞,expected_answer變量也無法解析求和。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM