python Invalid syntax Error : print - python

I try to write my first python program. But the print function is very special. I tried to write :
print ("success!")
very normal. but IDLE remind me that the code is wrong and "print" has been red. What should I do?

I think you are just seeing IDLE's syntax-highlighting feature. Keywords (and function names, variables etc.) are given different colours, in order to make the code easier to read (and spot errors like missing brackets etc.):
If you are seeing the same as this:
Then, you have nothing to worry about

Assuming this isn't just IDLE's syntax highlighting (hard to tell without the code in question)...
The reason for this odd behaviour has to do with a major change that was made in Python 3. In Python 2, print is a keyword. In Python 3, print is a function.
This has a number of implications:
In Python3, print requires parentheses
In Python2, print does not require parentheses by default
In Python2, print cannot be overridden by default (you cannot change what print does)
In Python3, print can be shadowed in a module, providing different behaviour for one application or another.
Now, what this means is that the syntax by default is different, but the good news is you can get the same syntax on both by putting as the first line in your module:
from __future__ import print_function
As a side note, this is a good idea since it ensures the same code will run on Python 2.7 and 3. So I add to all my Python modules these days:
from __future__ import print_function, division
(adding division there is good practice because of the way the division operator changed.)

the problem could be anywhere in the line that print appears in check for example if you have the right indention

Related

How do I define a keyword in Python to make the command shorter?

I would like to call a function in Python like a keyword. For motivation I have following problem:
Multiple variables can be deleted at once by using the keyword del.
x1,x2=1,1
del x1,x2
However,
x1,x2=1,1
del x1,x2,x3
leads to a name error if x3 is not defined. The convenience function Del deletes multiple variables independently of their existence (see this SE post):
def Del(*d:list[str])->None:
for i in d:globals().pop(i,None)
I can now call
x1,x2=1,1
Del('x1','x2','x3')
without getting an error message about non-existence of x3. However, for my new command Del I have to use brackets and quotes whereas for del I don't need them. The reason is that Del is a function, whereas del is a keyword.
How could I define Del as a keyword to call it like Del x1,x2,x3? Of course, any other method that saves quotes or brackets is welcome.
You cannot extend the grammar of Python via Python code.
Python is a mix between an interpreted and compiled language. This means that a process or program must convert the source code into another form before it can be executed. It is this process that ultimately understands the grammar that makes up Python (including all of the keywords, statements, and other syntax).
In order to extend or change the grammar, you need to change/modify the source code of that process. This is possible, but is not something that would be easy to do (you would have to modify the C code from which the Python binary is built). Additionally, even if you were successful, you could only use the new grammar for programs run using your custom binary. Anyone else running your code would receive syntax errors.

How to assign result to a variable AND print result in one command in Python?

In R, when you assign something to a variable, you can wrap your code in brackets to also print the result:
> a<-1+2
> a
3
>(a<-1+2)
3
Is there an equivalent feature in python?
No. You can't mix statements and expressions in the same "command".
You can, however, use ; to have both on the same "line":
a = 1 ; print(a)
# 1
There is no single statement which allows to that.
First we have assignment statements. Which allow to, well, make assignments.
And then you have either a print function (for Python 3.x) or a print statement (for Python 2.x). But neither of them cannot be mixed with the aforementioned assignemnt statement.
So no, you cannot do that in a single statement. You can, of couse, cheat that into one line by using ; but that is something not very readable which I would not recommend.
Bonun non-aswering rambling
From a readability point of view, assigning and printing are two very different things which should not be mixed.
Moreover, if you are (for instance) using a logging library instead of direct print usage, then the "single statement" you are looking for would become useless. In fact, I think that that is a rationale behind moving print from statement to function.
So, you don't have a single statement for assign-and-print and, I will add, that kind of statement doesn't seem a good idea in the Python language.

Running a python code within a python script [duplicate]

This question already has answers here:
How do I execute a string containing Python code in Python?
(14 answers)
Closed 9 years ago.
I want to do following. Script has some python code as a string (saved in a variable) and is it possible to run that code ?
Well, I know one way, writing that string to a file & running it, but I don't want that. Without creating any extra file, is it possible to run it ?
Here is a example :
let's assume my python file has following content
#this is a main python file
content = ''' print 'hello!'
print 'this is from sub python code' '''
print 'from main python'
The content string has a python code & I want to run it. Is it possible ?
Hope I am clear. Thank you !
I'll say this up front: This is a terrible idea, and depending on the source of the string a serious security risk.
That disclaimer out of the way, python has an exec function that executes a string containing python code. For example:
exec("print 2+2")
Edit: I originally used eval in my answer, which is useful for evaluating individual expressions, while exec can be used for more general execution of arbitrary python code in a string.
Relevant docs:
http://docs.python.org/2/reference/simple_stmts.html#exec
http://docs.python.org/2/library/functions.html#eval
Well you could use eval:
eval(content)
And that will do what you want, however it's not recommended, especially if someone else controls the content of content - it's not too hard to hack into your system if you have eval
Did you tried with exec method as per documentation that should do
exec "print 'Hello, World!'"
Depending on the code you are trying to execute, you may use eval() or exec. There are several differences between these two options:
eval() does what it should: it evaluates an expression and returns a value, not executes code. That means you may call functions, do some arithmetic, even use list comprehensions, generators or lambdas, but not execute python statements that aren't expressions (e.g. if, for, print in Python 2; however, in Python 3 print is a function and is ok).
eval() accepts more parameters than just a string. It gets locals and globals, two dictionaries, defining the scope environment. You may make evaluation nearly (though not really) safe for untrusted strings if you fill and pass these dictionaries to eval(). Probably, you may even redefine builtins by properly setting __builtins__ in globals. http://docs.python.org/2/library/functions.html#eval
exec also accepts globals and locals. See http://docs.python.org/2/reference/simple_stmts.html#exec . And it may execute everything. And it is virtually impossible to make it even relatively safe.

Dependencies. On loading modules for use in a function or a class, steer me?

I am working my way through some samples, and came up with this working answer - the challenge being set in the doctests:
def remove(sub, s):
"""
>>> remove('an', 'banana')
'bana'
>>> remove('cyc', 'bicycle')
'bile'
>>> remove('iss', 'Mississippi')
'Missippi'
>>> remove('egg', 'bicycle')
'bicycle'
"""
if sub not in s: return s # 1
from string import replace # 2
return replace( s, sub, '', 1) # 3
As a PyNoob I'd like to ask a few questions to get my bearings on all of this stuff vs the baggage I brought along with me from PHP.
On my line:
Is that the right place to bring in a module?
Is there an accepted way of checking the module was loaded and handling it?
2.
Is that the most efficient way of loading just the method I want?
3.
Overall really, is that the way you would solve this particular problem?
I guess I am also hunting for a steer vs your 'real world' expyrience. Is the string module so common that you'd more than likely have it loaded anyways?
If that is the case, how do you check a module is loaded?
Would it be rather pointless using exceptions to handle the string module not being findable because by default string is always going to be available?
(ps taken from Learning With Python ftw)
EDIT
OK, for those wondering, as has been pointed out - my question is misguided because I failed to understand that a string obj in Python already contains the replace() method.
This was caused because I failed to do something like:
>>> dir("a string")
which would have revealed all of the methods, including 'replace':
So then I could have followed that up by typing:
>>> "a string".replace.__doc__
Which would have spewed out:
'S.replace(old, new[, count]) ->
string Return a copy of string S with
all occurrences of substring old
replaced by new. If the optional
argument count is given, only the
first count occurrences are replaced.'
Now of course I knew this replace() method MUST exist somewhere, but I did not yet know how to look and discover for myself - the Python docs being frankly far too "loosely coupled" for me. Thanks for the answers - but am posting this EDIT in case any other similarly ignorant and bemused but willing Python advocate should stumble by.
By convention, imports are placed at the top of your module/script. It makes them easier to find for you and others reading your code. There are sometimes good reasons to put imports elsewhere, say a conditional import with significant overhead.
Another convention is not to 'check' that a module is loaded but instead to rely on the Python interpreter to raise a NameError exception if the object you are dereferencing is not available. Also note that multiple imports of the same module are safe as the import mechanism checks if it has been imported already.
You may want to read http://docs.python.org/tutorial/modules.html and http://diveintopython.net/object_oriented_framework/importing_modules.html
In this particular case, you don't need to import anything as .replace() is a method of the string object. The string module is largely redundant (not entirely, but it is imported rarely in my experience).
s.replace(sub, '')
Answer to 1: No, bring in modules at the top of your file, unless you need a conditional import.
And the rest of the answers are pretty useless, study this code (with the docs):
"banana".replace("an", "", 1)

In python, is there a "pass" equivalent for a variable assignment

I am using a library function called get_count_and_price which returns a 2-tuple (count,price). In many places I use both time and price. However, in some I only need time or price. So right now, if I only need count, I assign to (count,price) and leave the price unused.
This works great and causes no trouble in and of itself.
However...
I use Eclipse with PyDev, and the new version 1.5 automatically shows errors and warnings. One of the warnings it shows is unused variables. In the above example, it flags price as unused. This is the sort of behavior which is great and I really appreciate PyDev doing this for me. However, I would like to skip the assignment to price altogether. Ideally, I would like something like:
(count,None) = get_count_and_price()
Now as we all know, None cannot be assigned to. Is there something else I could do in this case?
I know I could do something like
count = get_count_and_price()[0]
but I am asking just to see if anyone has any better suggestions.
I think there's nothing wrong with using the [0] subscript, but sometimes people use the "throwaway" variable _. It's actually just like any other variable (with special usage in the console), except that some Python users decided to have it be "throwaway" as a convention.
count, _ = get_count_and_price()
About the PyDev problem, you should just use the [0] subscript anyway. But if you really want to use _ the only solution is to disable the unused variable warnings if that bothers you.
Using _ as severally proposed may have some issues (though it's mostly OK). By the Python style guidelines we use at work I'd normally use count, unused_price = ... since pylint is configured to ignore assignments to barenames starting with unused_ (and warn on USE of any such barename instead!-). But I don't know how to instruct PyDev to behave that way!
If you go to the Eclipse -> Preferences… window, you can actually specify which variable names PyDev should ignore if they're unused (I'm looking at the newest PyDev 1.5.X).
If you go to PyDev -> Editor -> Code Analysis and look at the last field that says "Don't report unused variable if name starts with"
Enter whatever names you want in there and then use that name to restrict what variable names PyDev will ignore unused warnings for.
By default, it looks like PyDev will hide unused variable warnings for any variables that have names beginning with "dummy", "_", or "unused".
As #TokenMacGuy said below, I'd recommend against using just "_" because it has special meaning in certain scenarios in Python (specifically it's used in the interactive interpreter).
We often do this.
count, _ = get_count_and_price()
or this
count, junk = get_count_and_price()
I'd rather name it _price instead, for these reasons:
It solves the conflict with gettext and the interactive prompt, which both use _
It's easy to change back into price if you end up needing it later.
As others have pointed out, the leading underscore already has a connotation of "internal" or "unused" in many languages.
So your code would end up looking like this:
(count, _price) = get_count_and_price()
I'll go after a Necromancer badge. :)
You said you're using PyDev. In PyDev (at least recent versions - I didn't check how far back), any variable name that starts with "unused" will be exempt from the Unused Variable warning. Other static analysis tool may still complain, though (pyflakes does - but it seems to ignore this warning in a tuple-unpacking context anyway).

Categories