I am trying to play with classes in python. I tried to run the following code.
class Abc:
def a(self):
print ("not to be seen")
def b(self):
print("inaccessible is")
self.a
say = Abc()
say.b
I am expecting the output as
inaccessible is
not to be seen
Instead I get the following output:
SyntaxError: invalid syntax
with say highlighted.
Please somebody point out what I am doing wrong.
Edit: I'm using IDLE GUI. Python 33 says the Python docs.
Python likes to make syntax very clear - the ()s after a function are not optional when calling a function without parameters like in some other languages.
You're not calling the functions just 'stating' them.
Try
class Abc:
def a(self):
print ("not to be seen")
def b(self):
print("inaccessible is")
self.a()
say = Abc()
say.b()
Here is the code working.
Syntactically, the code is valid.
You almost had it. You need to call the functions by adding (), like so:
class Abc:
def a(self):
print ("not to be seen")
def b(self):
print("inaccessible is")
self.a()
say = Abc()
say.b()
Actually I'm puzzled why your code throws a syntax error. In Python, it is valid to state a function.
OK, I could reproduce your error by installing idle for Python 3.3.0. I'm sorry that we all suspected that you didn't include the whole error message because IDLE doesn't produce more than a red SyntaxError: invalid syntax. There is nothing wrong with your code, nor your class definition.
I guess, you're just pasting the code as-is into your Python shell window. This way, things won't work because the indentation doesn't get produced correctly.
Try pasting the line class Abc: into your shell window and press Enter. You will see that IDLE automatically indents the next line with a tab. This is the correct indentation for the following line, so when you enter it, you need to paste def a(self): without any extra indentation! If you paste line by line and reduce the indentation by one where needed and terminate your class definition with an extra Enter, your code gets executed correctly.
However, you should better use the following method:
Paste your file into an editor and save it as whatever.py
In IDLE, choose File -> Open and open this file
A new window opens with your source code inside.
Now, press F5 or say Run -> Run Module
Your code will be executed and the result displayed in the Python Shell.
Or, even better, use Python directly in the shell by executing python whatever.py directly.
Related
I just moved to spyder for Python and the return function doesn't seem to work:
def test():
return 2
test()
The IPython console is empty. If I use print instead of return it works fine. Any idea?
I use python 3.7 with Spyder 4.1.5
Thanks in advance!
The editor is handling your code as a normal python script which means statements ala
test()
don't print their result. Instead you will need to do something with the value you are returning E.g. assign it to a variable or print it.
That you get the result of something displayed immediately is a special function of the python console and not normal python behaviour.
To actually print the result you have to call print(test())
so try this:
def test():
return 2
enter
>>press enter
print(test()
>>press enter
I would like to understand why f-strings do not print output in class methods. I would like to use their concise syntax for making breakpoints.
MWE:
class FStringTest:
def test(self):
print('why does this work')
f'but not this'
print(FStringTest().test())
f'yet this works'
Output:
why does this work
None
yet this works
Are you running this in Jupyter or an interactive python shell?
Because if you were, then the 'P' in REPL, which stands for print (R=READ,E=EVALUATE,P=PRINT,L=LOOP), will print the yet this works automatically for you without you explicitly calling the print function.
So:
why does this work
This is what the print inside your method returns.
None
You're seeing this because you're printing the value that your test() method is returning, and since it happens that it returns nothing (no return) it gives you this 'None' value.
yet this works
This is just what the REPL echoing back to you.
Note: Save this as a python script (.py) and try running it in an IDE like VSC, or via the command line using py <script_name>.py, it will not show you that last line of output.
I usually write scripts to calculate or process things for my own consumption. Now I'm trying to write scripts for others.
I use both IDLE and a terminal, but I like just like the IDLE interface and find it more helpful. Today I "discovered" that I can add triple-quoted text under class and def and see them in real time when using IDLE, and I realize I can use those to help others know how to use these classes and methods.
But if run from a terminal this is all lost.
Question: Is it only IDLE users who are seeing these cues while they are typing a line that uses the class or method, or is this something that people using terminal could see while typing if they wanted to? I know that one could type A.__doc__ to see it for example, but the pop-up window is really convenient and helpful.
class A(object):
"""hey A!"""
def __init__(self, x):
"""hey __int__!"""
self.x = x
def sqrx(self):
"""hey sqrx!"""
print self.x**2
(just to see what would happen if)
But if I do this from a terminal all these prompts disappear.
nothing.
The "triple-quoted messages" are docstrings, and they appear in different contexts.
For example:
When hitting ctrl+q (or whatever key is bound to the "Quick Documentation" action) in PyCharm:
There is also an option to display the quick documentation pop-up while typing.
When calling help on the function:
>> help(foo)
Help on function foo in module __main__:
foo()
foo's docstring
I can not tell you about other IDEs as I don't use them.
I have been using Python for a while and have had no problems with the IDE I've used (I've used WingIDE, now I use Spyder).
But when I started testing some code, which I typed on the editor, today, the return statement does not seem to work. Then I wrote even more basic tests which see what return does, and found out that other functions do not work properly as well.
For example for the function,
def test():
return 2
'''the code below is written in the editor'''
test()
print(type(test()))
print(test())
After running the code on the editor.
test() returns 'nothing' (but it's not actually 'nothing/None/blank space')
type(test()) returns 'nothing' (but it's not actually 'nothing/None/blank space')
print(type(test()) prints 'class 'int' '
print(test()) prints 2
But when I type test() on the console, it returns 2, and when I type type(test()) on the console, it returns class: int.
Note that the same results occur before and after I updated Spyder. And previously, the code in the editor functions the same way as the code in the console, as in typing test() in the editor would have returned 2 when I run the code in the editor.
Python/Spyder hasn't done anything this strange before, what happened?
Here's a visualization. Code in editor
Result after running code in editor displayed in the console
Assuming that the missing output of lines 116-118 is what upsets you:
The editor is handling your code as a normal python script which means statements ala test() don't print their result.
That you get the result of something displayed immediately is a special function of the python console and not normal python behavior.
To actually print the result you have to call print(test()) as you did in line 119-120
Update: After some testing in PyCharm
I got the following behavioir:
Copy&Pasting into the python console:
def test():
return 2
test()
>>press enter
indeed results in a blank output, but this:
def test():
return 2
>>press enter
test()
>>press enter
prints 2 as expected. So my conclusion is that Spyder is maybe not displaying the return value because it was executing a multi-instruction script instead of a single operation.
To expand Fabian's N. answer, Spyder has different evaluation models:
Run file, which is equivalent to python my_file.py.
Run line and Run cell, which copy the contents of a line or a cell to the IPython console and run it there. This model doesn't require adding print's to your code.
I am working in Aptana Studio and Python shell in the built-in terminal there. I am running some
rather long snippets of code on the shell command line. I keep tripping over typos so is there
a way to write all the code and copy and paste it onto the command line.
Yes, you can copy and paste code into the terminal, as long as complete definitions do not have blank lines in them.
You can paste:
def foo(bar):
print(bar)
return bar
but not
def foo(bar):
print(bar)
return bar
because the interpreter interprets the empty line as the end of the definition of foo.
The same applies to class definitions and suites (if, try, except, while, finally, etc.); no blank lines allowed anywhere in attribute and function definitions.
If it's not already configured that way, you may want configure your IDE to use IPython as your interpreter. With it, you can use the magic function %cpaste to allow you to paste full chunks of code. Just end your chunk with a line containing only -- to tell IPython that you're done.