输入的不平等检查无法正常工作

时间:2019-04-17 10:12:29

标签: python

我有一个函数,用户输入x_1和x_0的值,但是我想确保如果x_1和x_0小于0或大于R(某个常数),它会打印相应的错误消息。现在,无论x_0和x_1如何,它仍然会打印第一条错误消息。

G = 6.6741*10**-11
r_e = 6371000
r_m = 1737100
M_e = 5.9722*10**24  
M_m = 7.3420*10**22
R = 3.8440*10**8
w =  2.6617*10**-6
#defining a function such that f(r)=0#
def f(x):
    if x==0:
        return ('undefined')
    return (G*M_e)/x**2 - (G*M_m)/(R-x)**2 - w**2 * x

def sec(x_0,x_1):
            if x_1 or x_0>=R:
                print ('x_0 or x_1 must be less than R')
                raise SystemExit
            if x_1 or x_0<=0:
                print ('x_0 or x_1 must be greater than 0)
                raise SystemExit
            while x_0!=x_1:
                y=x_1-f(x_1)*(x_1-x_0)/(f(x_1)-f(x_0))#secant loop#
                x_0=x_1
                x_1=y
                print (x_1)
                if y==x_0:
                    print ('First Lagrange Point found to be {:5.4e}m from 
the Earth'.format(x_1))#print answer#
                    break

输出:

 sec(0,1)
 x_0 or x_1 must be less than R
 An exception has occurred, use %tb to see the full traceback.

SystemExit

C:\Users\jainv\Anaconda3\lib\site- 
packages\IPython\core\interactiveshell.py:3304: UserWarning: To exit: use 
'exit', 'quit', or Ctrl-D.
  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)



sec(10**7,10**8)
x_0 or x_1 must be less than R
An exception has occurred, use %tb to see the full traceback.

SystemExit

C:\Users\jainv\Anaconda3\lib\site- 
packages\IPython\core\interactiveshell.py:3304: UserWarning: To exit: use 
'exit', 'quit', or Ctrl-D.
  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

在这两种情况下,初始x_1和x_0都小于R,但我仍然收到“必须小于R”错误。

1 个答案:

答案 0 :(得分:1)

此:

if x_1 or x_0>=R:

这:

if x_1 or x_0<=0:

应为:

if x_1>=R or x_0>=R:

和:

if x_1<=0 or x_0<=0:

否则,它将分别评估if x_1,这只会在x_1 != 0True时出现。