Matplotlib - 来自输入

时间:2018-03-25 01:30:36

标签: python python-3.x matplotlib

我试图在Python 3.6中使用matplotlib显示一个带有公式的图表,但我遇到了一些问题。我试过了

import numpy as np
import matplotlib.pyplot as plt

def graph(x_range):
    x = np.array(x_range)
    y = 2*x
    plt.plot(x, y)
    plt.show()

graph(range(-10, 11))

工作正常,但如果我尝试用y = 2*x替换y = input()并尝试在终端输入2*x,则会收到错误消息,指出ValueError: Illegal format string "2*x"; two marker symbols

有关如何修复此错误的任何想法,或者是否有更好的方法来绘制用户给出的等式?

由于

2 个答案:

答案 0 :(得分:0)

如果您正在寻找相当轻量级的东西,并且#34;适合您的情况"并且没有评估所有数学表达式"那么白名单方法可能会很好地为您服务

 /users # Fetch a list of users
/users?occupation=programmer # Fetch a list of user with filter programmer
/users/123 # Fetch a user who has id 123

答案 1 :(得分:-1)

用此

替换y=2*x
y = eval(input('Enter formula'))

然而,这是一个非常肮脏的捷径。