← Back to all posts
invalid syntax

Hi everyone.
I get "invalid syntax" on this:
for i in range(1, n)
print (t[i], F[i])
..where t, F and n of course are defined. Why the error message?

Answered by JustARatherRidi (209) [earned 5 cycles]
JustARatherRidi (209)

Currently, the SyntaxError being raised in your repl is because you've left out a closing parenthesis on line 28. So line 28 should look like:

``F[i]=F[i-1]+dt*(-k3*F[i-1]+k4*R[i-1]*F[i-1])``

Change that, and the code seems to be working fine.

GustavW (1)

@JustARatherRidi
Yeah I wrote that expression "unfactorized", and then it worked. Of course it was something stupid like that. Thanks for checking the code!

u need a colon after the for i in range(1,n) and an indent on the print(t[i],F[i])

GustavW (1)

@15adilw Thanks for the quick response. The weird thing is that a colon generates the invalid syntax message. Without the colon the print-thing gets the error.

MATTHEWBECHTEL (125)

Did you define them correctly?

GustavW (1)

@MATTHEWBECHTEL I'm beginning to think I haven't. Here are the relevant parts of the program. It's a numerical solution to Lotka-volterra equations, using Euler.

n=200
dt=(tf-t0)/(n-1) #tidssteg
t=np.linspace(t0, tf, n) #tidsarray

R=np.zeros([n]) #Skapa array för kaniner och rävar
F=np.zeros([n])

R=R0
F=F0

for i in range(1,n):
R[i]=R[i-1]+dt(k1R[i-1]-k2R[i-1]F[i-1])
F[i]=F[i-1]+dt(-k3F[i-1]+k4R[i-1]F[i-1]

for i in range(n):
print (t[i], F[i])

MATTHEWBECHTEL (125)

I don’t know what Lotka-volterra equations or [email protected] is. And yeah, you should probably define those variables.

GustavW (1)

@MATTHEWBECHTEL It's just some first order differential equations, and Euler is a numerical method of solving them. F and t are defined arrays. The error implies that the program doesn't understand the print command. If something was undefined, wouldn't that generate another error, like "undefined blabla" ?

Vandesm14 (2319)

GustavW (1)

@Vandesm14 Sorry that wasn't a link I guess.

GustavW (1)

@Vandesm14
import matplotlib as mpl
import numpy as np
from matplotlib import pyplot as plt

R0= int(input("Ange antalet kaniner från början"))
F0=int(input("Ange antalet rävar från början"))

t0=0
tf=50

k1=2 #födslar kaniner
k2=0.01 #parameter för hur ofta rävar och kaniner möts
k3=0.8 #parameter för rävars död
k4=0.0002
n=200
dt=(tf-t0)/(n-1) #tidssteg
t=np.linspace(t0, tf, n) #tidsarray

R=np.zeros([n]) #Skapa array för kaniner och rävar
F=np.zeros([n])

R=R0
F=F0

for i in range(1,n):
R[i]=R[i-1]+dt(k1R[i-1]-k2R[i-1]F[i-1])
F[i]=F[i-1]+dt(-k3F[i-1]+k4R[i-1]F[i-1]

for k in range(1, n)
print (t[k], F[k])