我的代码不接受字符串,并且正在检查错误的变量

时间:2019-07-18 17:55:01

标签: python

所以我试图制作一个函数,绘制图,将f作为函数(我在shell中使用cos),将a和b作为b大于a的范围(默认B = 1和A = 0) ),间隔为n,m为Riemann sum(中心,左或右)的方法

但是问题是,当我运行代码并尝试将方法正确地捆绑时,它会执行以下操作。

import numpy as np
import matplotlib.pyplot as plt

def plot(f, a = 0, b = 1, m = str('center'), n = 10):


    v = 0
    par = (b - a)/1000
    x = np.arange(a, b, par)
    plt.plot(x, f(x), 'black')
    w = (b - a)/n

##This is juts plotting the graph, does not need to be grouped

    if b < a:
        raise ValueError('Value b must be greater than a', b)

##Check if b is greater than a

    if m != str('center') or m != str('left') or m != str('right'):
        raise ValueError('Value m must be one of the following: center, left, or right', b)

##Check if  m is valid

    if n < 0:
        raise ValueError('N must be a positive integer', n)

##Check if n is positive and an integer

    if m == 'center':
        d = w /2
        x2 = np.arange(a + d , b + d , w)
        plt.bar(x2,f(x2), align = 'center', color = 'blue',\
                edgecolor = 'black', width = w, alpha = 0.5)
        print("The estimation using", m ,"is", v)
        plt.show()

##Does Mid Point

    if m == 'left':
        x2 = np.arange(a , b , w)
        plt.bar(x2,f(x2), align = 'edge', color = 'red',\
                edgecolor = 'black', width = w, alpha = 0.5)
        print("The estimation using", m ,"is", v)
        plt.show()

##Does Left Point

    if m == 'right':
        x2 = np.arange(a + w, b + w , w)
        plt.bar(x2,f(x2), align = 'edge', color = 'orange',\
                edgecolor = 'black', width = -w, alpha = 0.5)
        print("The estimation using", m ,"is", v)
        plt.show()


##Does Right Point
Traceback (most recent call last):
  File "<pyshell#44>", line 1, in <module>
    p2.plot(f)
  File "C:\Users\Vincent\AppData\Local\Programs\Python\Python37-32\Project2.py", line 21, in plot
    raise ValueError('Value m must be one of the following: center, left, or right', b)
ValueError: ('Value m must be one of the following: center, left, or right', 1)

这是我收到的错误消息。我没有为m键入1,而是为b键入1,但是它正在以某种方式读取它。

2 个答案:

答案 0 :(得分:2)

您的if逻辑错误:

if m != str('center') or m != str('left') or m != str('right'):

这里需要and连接器; m必须始终不等于两个或三个单词,因此此条件始终为True。而是尝试

if m not in ("center", "left", "right"):

答案 1 :(得分:0)

更改此代码块:

if m != str('center') or m != str('left') or m != str('right'):
        raise ValueError('Value m must be one of the following: center, left, or right', b)

对此:

if m not in ['center', 'left', 'right']:
        raise ValueError('Value m must be one of the following: center, left, or right', b)

您的第一条语句检查m不是'center',不是'right'还是不是'left',并且由于m只能是一个,因此它将永远不会都是三个,因此它总是会引发异常。