首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何输入3个不同随机数的答案

如何输入3个不同随机数的答案
EN

Stack Overflow用户
提问于 2015-10-08 02:05:24
回答 1查看 49关注 0票数 0

我正在试着做一个简单的测验程序。但是在用户回答问题的代码中使用how do I get the input to be the same as the answer呢?

代码语言:javascript
运行
复制
 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")
EN

回答 1

Stack Overflow用户

发布于 2015-10-08 04:06:45

避免使用eval,修复缩进,地址注释,你会得到类似这样的结果。

代码语言:javascript
运行
复制
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!')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32999391

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档