如何让python解决由变量组成的数学问题

时间:2015-10-01 21:27:33

标签: python variables math random

import random

x = random.randrange(11)
z = random.randrange(11)
y = random.choice('-+*')

print("what is?", x, y, z)
ans1 = int(input())

if ans1 == (x, y, z):
    print("correct")
    score = score + 1
else:
    print("incorrect,the answer is", x, y, z)

输入示例和输出错误:

what is? 2 * 6

12

incorrect,the answer is 2 * 6

如何打印the answer is 12?我需要以某种方式评估表达式。

2 个答案:

答案 0 :(得分:1)

operator模块包含addsubmult

$current_user_id = $current_user->ID;
$post_email = $_POST['email'];
$esc_email = esc_attr($post_email);
$email_exists = email_exists($esc_email);
$user_by_email = get_user_by( 'email', $esc_email );
$email_user_id = isset($user_by_email->data->ID) ? $user_by_email->data->ID : 0;


    }elseif( $email_user_id && ($email_user_id != $current_user_id) ){
        $error[] = __('This email is already used by another user.  try a different one.', 'profile')

您可以将它们放入字典中查找:

>>> from operator import add, sub, mult
>>> add(5, 6)
11
>>> sub(5, 6)
-1
>>> mult(5, 6)
30

使用from operator import add, sub, mult ops = {'+': add, '-': sub, '*': mult} ans = ops[y](x, z) 并不是一条好路。

答案 1 :(得分:0)

添加

print (x,y,z) + 3

我得到了:

 Traceback (most recent call last):
  File "python", line 7, in <module>
 TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

这意味着你的(x,y,z)永远不会等于任何给定的整数,因为它不是一个整数。