如何输入3个不同的randoms的答案

时间:2015-10-07 18:05:24

标签: python-3.x

我正在尝试制作一个简单的测验程序。但how do I get the input to be the same as the answer用户回答问题的代码?

 import random

 print("what is your name \n")
 name=input()
 print("hello",name,"you will be asked 10 math questions goodluck")
 for i in range(10):
   op=["+","-","*"]
   num1=random.randint(0,10)
   num2=random.randint(0,12)
   operation=random.choice(op)
   eval(str(num1)+operation+str(num2)) 

   print(num1,operation,num2)

   while True:
     try:
        user= int(input())
        if user=answer:
           print("correct")
     except:
        print("invaild")

1 个答案:

答案 0 :(得分:0)

避免使用eval,修正无效,发表评论,你会得到类似的结果。

import random
import operator

operators = {'+': operator.add,
             '-': operator.sub,
             '*': operator.mul}


print("What is your name?")
name = input()

print("Hello {name} you will be asked 10 math questions, good luck.".format(name=name))

for _ in range(10):
    num1 = random.randint(0, 10)
    num2 = random.randint(0, 12)

    operator = random.choice(operators.keys())
    answer = operators[operator](num1, num2)

    print("{n1} {op} {n2} = ?".format(n1=num1, op=operator, n2=num2))

    try:
        user_input = int(input())
        if user_input == answer:
            print("Correct")
        else:
            print("Invaild")
    except ValueError:
        print('Please enter a number!')