是一个数学运算符,被归类为python中的一个整数 [英] is a mathematical operator classed as an interger in python

查看:115
本文介绍了是一个数学运算符,被归类为python中的一个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是一个被归类为整数的数学运算符。
例如为什么这个代码不起作用

in python is a mathematical operator classed as an interger. for example why isnt this code working

import random

score = 0
randomnumberforq = (random.randint(1,10))
randomoperator = (random.randint(0,2))
operator = ['*','+','-']
answer = (randomnumberforq ,operator[randomoperator], randomnumberforq)
useranswer = input(int(randomnumberforq)+int(operator[randomoperator])+      int(randomnumberforq))
if answer == useranswer:
print('correct')
else:
    print('wrong')


推荐答案

您不能将运算符连接到几个数字并期望对其进行求值。您可以使用 eval 来评估最终字符串。

You can't just concatenate an operator to a couple of numbers and expect it to be evaluated. You could use eval to evaluate the final string.

answer = eval(str(randomnumberforq)
              + operator[randomoperator] 
              + str(randomnumberforq))

完成您尝试的更好方法是使用运算符模块中的函数。通过将功能分配给列表,您可以选择随机调用哪一个:

A better way to accomplish what you're attempting is to use the functions found in the operator module. By assigning the functions to a list, you can choose which one to call randomly:

import random
from operator import mul, add, sub    

if __name__ == '__main__':
    score = 0
    randomnumberforq = random.randint(1,10)
    randomoperator = random.randint(0,2)
    operator = [[mul, ' * '],
                [add, ' + '], 
                [sub, ' - ']]
    answer = operator[randomoperator][0](randomnumberforq, randomnumberforq)
    useranswer = input(str(randomnumberforq) 
                       + operator[randomoperator][1] 
                       + str(randomnumberforq) + ' = ')
    if answer == useranswer:
        print('correct')
    else:
        print('wrong')

这篇关于是一个数学运算符,被归类为python中的一个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆