如何创建一个循环函数显示数字是奇数还是偶数?



我想创建一个依赖于一个变量的值的循环,无论它是奇数还是偶数,但是代码显示了一个错误。这个想法是,如果'count'是偶数,那么c被用作一个变量。如果'count'是奇数,则使用a。大多数是非常混乱的,我知道这一点,但问题是为什么代码显示计数函数和"else"部分,显示语法错误

**#Importing the calculus library
import sympy

#Specifying and defining values of the function
print("Function?")
y = sympy.Function('y')
y = 0.5
x = sympy.symbols('x')
print("Absolute uncertainty?")
n = sympy.symbols('n')
n = 0.001
print("Degree of root?")
m = sympy.symbols('m')
m = 2
s = sympy.symbols('s')
f = sympy.Function('f')
f = (1+x)**(1/m)
#Calculating absolute relative error as the stopping variable
print(f"Stopping variable: {s}")

#Creating the loop
count = 1
a = sympy.Function('a')
a = sympy.diff(f)
af = a.subs(x,0)
j = sympy.Function('j')
j = 1+((1/sympy.factorial(count))*af)*x**(count)
def main():
global a
global af
global count 
global j 
global s
count = count+1
b = sympy.Function('b')
b = sympy.diff(a)
bf = b.subs(x,0)
r = sympy.Function('r')
r = j+((1/sympy.factorial(count))*bf)*x**(count)

g = sympy.is_even(count)
g = ask(Q.even(count))
if g == True:

count = count+1
a = b
af = a.subs(x,0)
j = r+(1/sympy.factorial(count))*af*x**(count)

main()

else:
ans = r
res_ans = ans.subs(x, y-1)
print(f"Answer: {res_ans}")       
main()

**

我可以修复代码,不产生任何错误,如下

# Importing the calculus library
import sympy
# Specifying and defining values of the function
print("Function?")
y = sympy.Function('y')
y = 0.5
x = sympy.symbols('x')
print("Absolute uncertainty?")
n = sympy.symbols('n')
n = 0.001
print("Degree of root?")
m = sympy.symbols('m')
m = 2
s = sympy.symbols('s')
f = sympy.Function('f')
f = (1+x)**(1/m)
# Calculating absolute relative error as the stopping variable
print(f"Stopping variable: {s}")
# Creating the loop
count = 1
a = sympy.Function('a')
a = sympy.diff(f)
af = a.subs(x,0)
j = sympy.Function('j')
j = 1+((1/sympy.factorial(count))*af)*x**(count)
def main():
global a
global af
global count 
global j 
global s
count = count+1
b = sympy.Function('b')
b = sympy.diff(a)
bf = b.subs(x,0)
r = sympy.Function('r')
r = j+((1/sympy.factorial(count))*bf)*x**(count)

g = sympy.simplify(count).is_even
g = sympy.ask(sympy.simplify(count).is_even)

if g == True:
count = count+1
a = b
af = a.subs(x,0)
j = r+(1/sympy.factorial(count))*af*x**(count)

else:
ans = r
res_ans = ans.subs(x, y-1)
print(f"Answer: {res_ans}")
main()

通过在函数def main():中移除main()的调用。但是由于我不知道你想要实现什么,而且我对SymPy的知识也不了解,所以我无法进一步帮助你。

您可以在所有部分中看到https://github.com/dudung/py-jupyter-nb/blob/main/src/so/75201156.ipynb上的结果第1部分第二部分) .

如果main()仍然放在else之前,在固定缩进后,它不会停止,因为它递归地调用自己。

相关内容

  • 没有找到相关文章

最新更新