简体   繁体   中英

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

I want to make python ask 10 questions and a user to have to input their answers which works. However I also want python to say whether this is correct or not by using the code below but this does not work and only moves onto the next question. Could anybody tell me why? Or what I need to change? Also how do I make this ask 10 question specifically using the variables I have and a while loop?

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)

All of your comparisons in your while statement are being done against list s instead of the randomly chosen element.

You likely want to do something like this:

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)

There are many other ways to improve the structure of the code, which might make it look like this:

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

This uses a dedicated getInteger function to handle invalid input, uses a dictionary and functions being first-class objects to choose which "actual" operator function to use, uses += , uses range and for , instead of a while loop, uses sane constants...the list of possible improvements is large.

Here is what was wrong with the code

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)

As Kupiakos said, there is a lot of ways to optimize the code and he already covered most of them. I will point out to fixes for the mentioned problems.

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

Good luck with your students.

Below is the solution to your problem:

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

The operands variable is not required here, instead you can pass the + operator as a string itself. Also expected_answer variable is not able to resolve the summation as operand1 and operand2 are being passed as a list but not as an int.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM