Python newbie problems - python

I just finished watching this video https://www.youtube.com/watch?v=qO4ZN5uZSVg, and even though it teaches 2.0 edition Python, some notes pop up for the 3.0 uses of python. Nevertheless, in the end, some challenges are provided, one of them is this:
def returnTwo():
return 20,30
x,y = returnTwo()
print(x,y)
Whenever i try to see what the conclusion will be, this is what comes up
def returnTwo():
return 20,30
(red X in the 3.5 Shell) x,y = returnTwo()
SyntaxError: invalid syntax.
What can I do?

The python shell allows to interactively run commands. This is very useful when doing quick calculations of to quickly check some small pieces of code.
In this case, you want to define a function. Defining a function is just that: a definition. Later on, you actually call the function and make it run. The issue here is that a function is (often) defined in more than one line. That means, you actually hit enter before you finish to define the function. For that reason, you tell the shell that you finished with an extra enter:
This also applies if you define your function in a single line:
And that's the reason why you get a SyntaxError: The line x, y = returnTwo() is supposed to be in the function, but for that, it would need to indented (to the level of return 20, 30):
Like #jim said, just try pressing enter until you get the >>> prompt again!
Remember that the three little dots do have a meaning too.
This question was already answered in the comments by #helios35 and #jim!
I just elaborate and post as an answer here for future users.

Related

Why does the Python console repeat back what input into it?

When I write something into the python console, it repeats back what I write.
Like if I write 1, it displays 1 in output, and if I write True it gives True.
Why is this?
Example:
>>1
1
>>True
True
What actually happens in background?
You're typing into a REPL. It Reads input, Evaluates it, Prints the result, then Loops back and starts again.
You're having it read the number 1, evaluate it (although it's just a number), then print the result of the evaluation (the number). After that it waits for more input to be entered so it can run again.
If you typed a more complicated expression, it would be evaluated as well. 1 + 1 will show 2, and [1] * 5 will show [1, 1, 1, 1, 1] for example.
If you want to think about how this is achieved in terms of code, the most basic implementation of a REPL would be something along the lines of:
while True:
user_input = input(">> ")
result = eval(user_input) # eval evaluates a string as code
print(result)
Code similar to this (although likely far more complicated) is just running in the background.
You're talking about one way to invoke the Python interpreter.
This is a computer program designed to accept Python statements, and to print the evaluated result of each one.
In your examples, your statements are simple expressions that evaluate to pretty much what you typed in.
More complex examples include expressions like 1+1, or function calls.
How this works "in [the] background" is far too large a topic for a Stack Overflow answer, but you could study the Python project's source code if you really wanted to know what kind of programming constructs have been used to produce this computer program.
Short answer:
Jeffrey Elkner in his book says that:
When you type a statement on the command line, Python executes it. The interpreter does not display any results....
An expression is a combination of values, variables, operators, and calls to functions. If you type an expression at the Python prompt, the interpreter evaluates it and displays the result, which is always a value
More details:
You know, what a computer really understands is consecutive zero's and one's.
Your hardware is the one who specifies the format of these one's and zero's.
it is hard for people to know about how to order a hardware to do a task. To solve this problem,high level languages and VHLL(very high-level programming languages) such as Python are created.
How do they solve the problem?
These languages are more similar to human languages. In addition, each of these languages has some tool to convert the code to a machine-readable format! (of course, without this, they were worth nothing)
Actually the tools used to convert a human-readable format to machine-readable format, fall into one of these categories: Interpreters, Compilers, Hybrid approach(used in languages like C# and Java).
Python code is executed using an Interpreter!
So when you type an expression or an statement, in python shell, the interpreter comes and executes the statements and evaluates the expressions in your code!
One final point:
Python docs considers expressions, just as a subset of statements(look at the link).

Python IDLE with Python 3.5.2 "crashing"

Okay, so let me just say beforehand: I am new to Python. I was just experimenting with IDLE and then I had this weird "crash". I put "crash" inside speech marks because I'm not sure if it qualifies as a crash, as rather than the program just crashing the way a normal program would in Windows, it still runs, but whenever I press enter and try and get it to accept new text it doesn't do anything. E.g. if you try and type "print('a')" and then hit enter it just goes to the next line (and doesn't print 'a'). I tried to make a simple function which converted an integer to a string where each character in the string was either a '1' or a '0', forming the binary number representing said (unsigned) integer.
>>> def int_to_str(int_in):
str_out=''
bit_val=1<<int_in.bit_length()
while(int_in>0):
if(int_in>bit_val):
str_out+='1'
int_in-=bit_val
else:
str_out+='0'
bit_val>>=1
return str_out
>>> print('a')
print('c')
Basically, it becomes completely unresponsive to my input, and allows me to edit/change "print('a')" even though I shouldn't be able to if it had actually "accepted" my input. Why is this? What have I done wrong/messed up?
Also, I made sure it isn't something else I was previously messing around with by closing the shell and opening it again and only putting in said code for the "int_to_string" function, and I haven't changed any settings or imported any modules before hand or anything like that (in case it matters).
EDIT: I tried reinstalling, and that helped a bit in that I can now do other stuff fine, but the moment I try to use the "str_to_int()" function, it has this same weird behaviour of not accepting/interpreting any more user input.
Your while loop never terminates, you need to re-arrange your logic. Printing variables can be an effective debugging tool - like this:
>>> def int_to_str(int_in):
str_out=''
bit_val=1<<int_in.bit_length()
while(int_in>0):
print(int_in, bit_val)
if(int_in>bit_val):
str_out+='1'
int_in-=bit_val
else:
str_out+='0'
bit_val>>=1
return str_out
If your program seems to be going on too long you can stop it with ctrl-c.

Call a function from main script in an imported file

Before I begin, I know there are many questions that sound a lot like this one, but my question is a little different... So here it is...
As the title may of suggested, I am trying to call a function defined in my main.py script in an imported module. However, this situation is a bit different than that of a circular import situation. I have been doing a lot with pygame recently, and decided that I was gonna make a module that contains classes for buttons, text, sounds, and so on. But I want this file to be generic so it can be used with any game or application I make. Buttons usually have draw functions and stuff like that, so I can easily pass those variables into the functions without problem. The problem comes when I get to the part where I want to check if the button is clicked, and if it is do something. I want to have it set up so that I can pass in a string argument for a command, and use the eval() command on it (python 2.7). However, it throws the error of the function not being defined. I know why this is, but I want to see if there is anything I can do to get around this issue to keep the module as "generic" as possible. Below is a basic set of code to help explain what I want to do.
module1.py
class Button(object):
def __init__(self,x=0,y=0,image=None,command=""):
self.x = x
self.y = y
self.image = image
self.command = command
"""
Image this part filled with draw commands and stuff...
These functions work perfectly fine
"""
#Now here is the issue - local is mouse position
def checkClick(self, local):
#If statments here to determine if mouse over button and
#if mouse is clicked... The part below fails
eval(self.command)
main.py
import module1
import pygame
def quitgame():
pygame.quit()
quit()
local = pygame.mouse.get_pos()
b = module1.Button(command="quitgame")
#At this point lets assume that the mouse is overtop the button and the
#following function in the button will run
b.checkClick(local)
The error, as I said before states that the function I try to call is not defined. I have found a workaround for this, so I don't want answers that tell me how I can change this so it does not take a command as input. I would like however, to make it so I can input a command as an argument. Maybe I am not inputing a command the way I should, but I would like to do it like this, especially because the tkinter module allows you to enter a command as input/a variable. Maybe there is not a way to do this like I wish, but I really want to keep this code as reusable as possible with no changing required between games, and I would rather not have to put this code into my games/applications every time I make them (like I said before the code example I gave was just an example, my actual button code is much larger than what I did above). Like I said before as well, I know that there are many questions that are just like this one, but they have not helped me at all with this issue. The others suggested using scripts that are imported as well which contain addition variables and such, but I would rather not do this. Also, I have a workaround that completely gets rid of the issue, but it is not nearly as neat or easy as this would be.
As always, any help would be appreciated and thanks ahead of time for your answers in case I don't get back to you right away.
I want to have it set up so that I can pass in a string argument for a command, and use the eval() command on it (python 2.7).
No, no, no. Pass it a function:
# In main.py
b = module1.Button(command=quitgame)
# In module1.py
def checkClick(self, local):
...
self.command()
eval is almost never the right tool for any job.
If you don't want to define a function just to pass it as a command parameter, you can use a lambda for short (single-expression) functions:
b = module1.Button(command=lambda: do_whatever(some, arguments))

Does python have an EXIT_SUCCESS constant?

I'm returning 0 all over the place in a python script but would prefer something more semantic, something more readable. I don't like that magic number. Is there an idea in python similar to how in C you can return EXIT_SUCCESS instead of just 0?
I was unable to find it here:
https://docs.python.org/3.5/library/errno.html
I'm returning 0
return is not how you set your script's exit code in Python. If you want to exit with an exit code of 0, just let your script complete normally. The exit code will automatically be set to 0. If you want to exit with a different exit code, sys.exit is the tool to use.
If you're using return values of 0 or 1 within your code to indicate whether functions succeeded or failed, this is a bad idea. You should raise an appropriate exception if something goes wrong.
Since you discuss return here, it seems like you may be programming Python like C. Most Python functions should ideally be written to raise an exception if they fail, and the calling code can determine how to handle the exceptional conditions. For validation functions it's probably best to return True or False - not as literals, usually, but as the result of some expression like s.isdigit().
When talking about the return value of a process into its environment you caonnt use return because a module isn't a function, so a return statement at top level would be flagged as a syntax error. Instead you should use sys.exit.
Python might seem a little minimalist in this respect, but a call to sys.exit with no arguments defaults to success (i.e. return code zero). So the easiest way to simplify your program might be to stop coding it with an argument where you don't want to indicate failure!
As the documentation reminds us, integer arguments are passed back, and string arguments result in a return code of 1 and the string is printed to stderr.
The language doesn't, as far as I am aware, contain any constants (while it does have features specific to some environments, if it provided exit codes their values might need to be implementation- or platform-specific and the language developers prefer to avoid this where possible.

Python REPL: issuing commands in advance to execute after block

This is a bit of an odd question; it came up in the context of a tool that exposes a Python API, which we spend a lot of time querying interactively from the REPL. The particular idiom causing issues is something like this:
for var in slow_generator_of_giant_list():
stats = update(stats, var)
print stats
To enter this at the REPL, I can type this:
>>> for var in slow_generator_of_giant_list():
... stats = update(stats, var)
...
If I now attempt to type the print, I get a syntax error due to improper indentation. (Or else I put the print inside the loop and do it on every iteration.)
But if I hit enter to go to the next line, the loop runs immediately, and I have to wait for it to finish, or type the print command in the face of possible output coming at me, etc.
Obviously I can define a function containing the above, and it might be worth saving into a file anyway, but in the general case we're constructing these on the fly, and it would be nice to have a way to "schedule" a command to run after the end of a loop from the REPL. In a language with block delimiters, I could of course put it after the ending delimiter (and any necessary statement separator). But my coworkers and I were stumped trying to do something similar here.
Is there perhaps an ugly abuse of Pythonic syntax that will do the trick that my coworkers and I couldn't think of? Or a recommended way to avoid the problem while still making it easy to throw together ad hoc interactive queries?
Thanks for any pointers.
Not beautiful, but this should work:
>>> mygen = slow_generator_of_giant_list()
>>> try:
... while True: stats = update(stats, mygen.next())
... except StopIteration:
... print stats
...
I would just say that you would find it easier just to not use the interactive shell for this.
It's not much effort to save a file and run it. You only have to keep it around for as long as you use it.
I actually have found this answering on SO. I keep a file open in my text editor with a terminal in the right directory, and just use it as a scratchpad for mocking up answers in.

Categories

Resources