Functions in Python 2.7 vs 3.x - python

I'm new to Python. I've been trying to familiarize myself with Numpy, Scipy, and Matplotlib, as I have a background in the sciences, and hope to make myself a more competitive candidate for work in neuroscience laboratories.
I've been browsing through the Matplotlib documentation, trying to learn by example. I will reference an example from the following URL: http://matplotlib.org/users/pyplot_tutorial.html
I am under the impression that these examples are written in Python 3.x, and that I am having trouble because I am using Python 2.7. I am using 2.7 because some of the libraries I wanted weren't available for 3.x.
The website gave an example of using subplots. Their code is as follows:
import numpy as np
import matplotlib.pyplot as plt
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
This is supposed to return a Figure like this: http://i.stack.imgur.com/ejNDu.png
When I copy the same code into IDLE, it gives me an error. On the line
t1 = np.arange(0.0, 5.0, 0.1)
, IDLE tells me that "t1" is invalid syntax.
My first question: What is the problem with using t1 as a variable?
If I copy in similar code, but with a few things tweaked, I can avoid this error. However, I am then presented with another error. When I add the line equivalent to
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
, IDLE presents me with the error:
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
plt.plot(ty, f(tx), 'bo', ty, f(ty), 'k')
NameError: name 'f' is not defined
I'm not sure how Python expects me to define "f" separately from the function "f(t)".
My second and MAIN question: Could somebody please explain why "f" must be defined separately? How do I use functions like this correctly in Python 2.7?
If anybody needs me to explain the Numpy/Matplotlib mechanisms used here, I will do my best to explain how they work to bring about the graphs.

For the syntax error, check the line or two before. t1 is a perfectly valid variable name (the rules are similar to various other languages: variable names can contain letters, numbers and _, but can't start with a number) - but if you've forgotten a close bracket or similar above, then the interpreter will get confused and tell you you can't have an assignment statement there (newlines don't count as 'end of statement' if they're inside (), {} or [], or if the last character before the newline is \).
Defining a function does give you a variable in that namespace with that name - you don't need to define f separately. It is difficult to tell without seeing your exact code, but what has likely happened is either you have defined it in a different scope (so the name isn't visible), or you have renamed the function to something other than f.

Try typing everything again, in a new window. 'f' isn't supposed to be defined separately.

That error of invalid syntax seams to appear because the missing of a new line, and an unexpected indentation.
In the IDLE, after defining the function f(t) you have to press again <return> to finish the declaration of f(t) - putting an empty line after the declaration of f(t).
If you don't add that additional new line in the IDLE, you would get a syntax error because the unexpected indentation, and the definition of f(t) wouldn't be finished, so you also get the next error that says 'f' is not defined.

Related

How can I solve syntax error for the following code in Python 2.7?

I have used the following code for optimizing a problem via pyomo, coopr.
However the compiler gives an error, as follows:
invalid syntax
I tried to use correct syntax but I can not find the error:
model = AbstractModel()
model.x = Var(initialize = 1.5)
model.y = Var(initialize = 1.5)
import pyomo
from coopr.pyomo import *
def rosenbrock(model):
return (1.0-model.x)**2 \
+ 100.0*(model.y - model.x**2)**2
model.obj=Objective(rule=rosenbrock, sense=minimize)
SyntaxError: invalid syntax
That code appears to be syntactically valid. Indeed I have just successfully compiled it in Python 3.6
Two possibilities occur to me:
There is a problem with your line continuation. Note that the backslash
must be followed only by exactly the new line character. If you have additional white space then this will cause an error. For that reason, Python programmers are recommended to avoid line continuation.
The environment in which this code is running is a specialised embedded Python with some special constraints of which I am not aware.
Hope one of these helps ...

Python arrays issue

I tried writing the code for a problem, but the module won't run. It says invalid syntax, but it's not highlighting anything.
The code: http://pastebin.com/cJVNBcYE
The problem: http://pastebin.com/p8E0E0Nj
I don't understand why it's not working.
I have numDealers set as a variable so that info can be entered in the program. The arrays are all defined. I have index=0 and x=1 to set up the loop for the numDealer arrays for sales and commission. I have another array=index section to calculate commissions. And then I have the prints set up.
Why isn't the program working? I don't understand.
Please post code in future, with a full traceback of the error. However:
else print(sales[index]) and print(comm[index])
should be:
else:
print(sales[index]) and print(comm[index])
i.e. you are missing a colon
I'm a bit puzzled by the and. It means that the second print will only be executed if the first fails (unlikely). Did you mean:
else:
print(sales[index])
print(comm[index])
?
By the way, it appears you are not using arrays but lists. The Python standard library includes a module called array https://docs.python.org/3/library/array.html which you do not appear to be using. So don't have a list called array, that collides with the standard library module name, and can cause no end of confusion.

Python's math module & "Think Python"

I'm stucked on the chapter 3.3 "Math functions" of "Think Python".
It tells me to import math (through the interpreter).
Then print math and that I should get something like this:
<module 'math' from '/usr/lib/python2.5/lib-dynload/math.so'>
Instead I get <module 'math' <built-in>>
Anyway that's not the problem. Though I wasn't able to find a 'math.so' file in my python folder. The most similar file is named test_math.
The problem is that I'm supposed to write this:
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
When I write the first line it tells me this:
Traceback <most recent call last>:
File "<stdin>", line 1, in <module>
NameError: name 'signal_power' is not defined
On the book says "The first example uses log10 to compute a signal-to-noise ratio in decibels (assuming that signal_power and noise_power are defined)."
So I assume that the problem might be that I didn't defined 'signal_power', but I don't know how to do it and what to assign to it...
This is the first time that I feel that this book is not holding my hand and I'm already lost. To be honest I don't understand this whole chapter.
By the way, I'm using Python2.7 and Windows XP. I may copy and paste the whole chapter if anyone feels that I should do it.
Python is my first language and I already tried to learn it using "Learn Python the hard way" but got stucked on chapter 16. So I decided to use "Think Python" and then go back to "Learn Python the hard way".
You've figured it out - you have to set signal_power's value before using it. As to what you have to set it to - it's not really a Python related question, but 1 is always a safe choice :) While you are at it, don't forget to define noise_power.
You indeed need to assign a value to both signal_power and noise_power. The author likely left them out because the values are arbitrary. Even when supplied with exact values in a text, you should also play around with the values. After all, there's not much point in having you type anything in if the results on the screen are the same as on the page.
signal_power = 100
noise_power = 17
This particular example defines the mathematical relationship between variables. If it were presented as such, it wouldn't be such a mystery that exact values were left out, as they would be supplied by someone when using the formula. The same holds for the code sample.
The book is for an older version of python apparently. But that is unrelated to your actual question.
Try defining signal_power. For example
signal_power = 0
You can't use a variable without defining/declaring it first. When you say ratio = signal_power / noise_power,
you're trying to access two variables that the interpreter has never heard about.
Before telling the machine what to do with the variables, you have to introduce them to it first.
You do this by declaring them:
signal_power = 123
noise_power = 321
You can define them as any number you want, not only 123 and 321, but you must define them before using them.

Error using cv.CreateHist in Python OpenCV as well as strange absence of certain cv attributes

I am getting an error (see below) when trying to use cv.CreateHist in Python. I
am also noticing another alarming problem. If I spit out all of the attributes
of the cv module into a file, and then I search them, I find that a ton of
common things are missing.
For example, cv.TermCriteria() is not there; cv.ConnectedComp is not there; and
cv.CvRect is not there.
Everything about my installation, with Open CV 2.2, worked just fine. I can plot
images, make CvScalars, and call plenty of the functions, like cv.CamShift...
but there are a dozen or so of these hit-or-miss functions or data structures
that are simply missing with no explanation.
Here's my code for cv.CreateHist:
import cv
q = cv.CreateHist([1],1,cv.CV_HIST_ARRAY)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: x9y��
The weird wingding stuff is actually what it spits out at the command line, not a copy-paste error. Can anyone help figure this out? It's incredibly puzzling.
Ely
As for CvRect, see the documentation. It says such types are represented as Pythonic tuples.
As for your call to CreateHist, you may be passing the arguments in wrong order. See createhist in the docs for python opencv.

Help with Python UnboundLocalError: local variable referenced before assignment

I have post the similar question before,however,I think I may have misinterpreted my question,so may I just post my origin code here,and looking for someone can help me,I am really stuck now..thanks alot.
from numpy import *
import math as M
#initial condition All in SI unit
G=6.673*10**-11 #Gravitational constant
ms=1.9889*10**30 #mass of the sun
me=5.9742*10**24 #mass of the earth
dt=10 #time step
#Creat arrays
vs=array([[0,0,0]]) #1st element stand for x component of V of earth
ve=array([[29770,0,0]])
rs=array([[0,0,0]])
re=array([[0,1.4960*10**11,0]])
#First update velocity in order to start leapfrog approximation
fs=-G*ms*me*((rs-re)/(M.sqrt((rs-re)[0][0]**2+(rs-re)[0][1]**2+(rs-re)[0][2]**2))**3)
fe=-fs
vs=vs+fs*dt/ms
ve=ve+fe*dt/me
n=input('please enter the number of timestep you want it evolve:')
#update force
def force(n,ms,me,rs,re,G):
rs,re=update_r(rs,re,n,dt)
fs=-G*ms*me*((rs-re)/(M.sqrt((rs-re)[0][0]**2+(rs-re)[0][1]**2+(rs-re)[0][2]**2))**3)
fe=-fs
return fs,fe
#update velocities
def update_v(n,vs,ve,ms,me,dt,fs,fe):
fs,fe=force(n,ms,me,rs,re,G)
i=arange(n)
vs=vs+fs[:]*i[:,newaxis]*dt/ms
ve=ve+fe[:]*i[:,newaxis]*dt/me
return vs,ve
#update position
def update_r(rs,re,n,dt):
vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)
i=arange(n)
rs=rs+vs[:]*i[:,newaxis]*dt
re=re+ve[:]*i[:,newaxis]*dt
return rs,re
#there is start position,v,r,f all have initial arrays(when n=0).
#then it should calculate f(n=1) then use this to update v(n=0)
#to v(n=1),then use v(n=1) update r(n=0) to r(n=1),then use r(n=1)
#update f(n=1) to f(n=2)....and so on until finish n.but this code seems doesnt do this,,how can I make it? –
when i call force python gives:
please enter the number of timestep you want it evolve:4Traceback (most recent call last):
File "<pyshell#391>", line 1, in <module>
force(n,ms,me,rs,re,G)
File "/Users/Code.py", line 24, in force
rs,re=update_r(rs,re,n,dt)
File "/Users/Code.py", line 39, in update_r
vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)
UnboundLocalError: local variable 'vs' referenced before assignment
can anyone give me some tips?thanks......
where do you call force in this code?
In any event, the problem is in update_r. You reference vs in the first line of update_r even though vs is not defined in this function. Python is not looking at the vs defined above. Try adding
global vs
as the first line of update_r or adding vs to the parameter list for update_r
In the first line of update_r, you have vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe). Look at the function that you are calling. You are calling update_v with a bunch of parameters. One of these parameters is vs. However, that is the first time in that function that vs appears. The variable vs does not have a value associated with it yet. Try initializing it first, and your error should disappear
Put an additional global statement containing all your globals after each def statement. Otherwise, all globals are transformed into locals within your def without it.
def update_v(n,vs,ve,ms,me,dt,fs,fe):
global vs, ve, ...
On line 39 you do
vs,ve=update_v(n,vs,ve,ms,me,dt,fs,fe)
while you are inside a function.
Since you defined a global variable called vs, you would expect this to work.
It would have worked if you had:
vs_new,ve_new = update_v(n,vs,ve,ms,me,dt,fs,fe)
because then the interpreter knows vs in the function arguments is the global one. But since you had vs in the left hand side, you created an uninitialized local variable.
But dude, you have a much bigger problem in your code:
update_r calls update_v, update_v calls force, and force calls update_r - you will get a stack overflow :)
I got that error when my class name was assigned to a variable that is called exactly like its name. example ClassName = ClassName. You may do this if you come from .Net

Categories

Resources