python fast writing of a variables name and value - python

I am porting some code from matlab to python and i see that I miss fast variable content inspection and printing of the matlab (in scripts) like shown below.
a=6
a =
6
Same thing in python:
a=6 ; print "a = \n",a
a =
6
In a matlab script if you write an assignment like shown above, without a semicolon at the end, it prints just like that. You can write the whole script like that, and later shutdown all those lines with semicolons. It is very helpful for early debugging purposes.
Just now, I scanned all lines with assignments, and put prints like
; print "a", a
at the end of them. I immediately saw the problem with the code.
Is there a way to type less for this purpose?

The ipython (or plain python) interactive interpreter already shows you the value of anything you type into it.
The only reason you don't see anything for a=6 is that, in Python, assignment is a statement, not an expression, and therefore it doesn't have a value.
But if you just type a, that's an expression, with a value, and it will show you the value:
In [8]: a=6
In [9]: a
Out[9]: 6
If that's not good enough, and you want it to automatically show you the name and value for any assignment statement… that's not impossible, but it's much harder than it's worth.

Related

python To efficiently use the result of function in if statement

Is there any other code form, that one can both use a function in if statement and get the value of function without executing the function twice?
For example,
There exists a function, fun1(arg), which takes an hour to return its result (The result value can be either None or some int)
and I want to do some further calculation(for example get its squared value) only if the result from fun1 is not None.
This will be done by:
result = fun1(arg)
if result:
result = result * result
Is there any shorter form such as
if (result = fun1(arg)):
result = result * result
in python?
It may be more "clean" in a code manner, it is possible in C/C++ to do the 2nd one. Not in Python to the best of my knowledge. Moreover, the two examples you gave have the exact same needs in term of memory and computation. So it would be totally equivalent to use any of these two.
The two are absolutely identical. So my answer would be, go with your first method that you already know how to code đź‘Ť.
Do not over complicate when it is not necessary, it is a good piece of advice in general.
This is coming in a future version of python. See the following PEP
https://www.python.org/dev/peps/pep-0572/
It'll be known as an assignment expression. The proposed syntax is like;
# Handle a matched regex
if (match := pattern.search(data)) is not None:
# Do something with match
No you can't do this. Statements in Python not work as expressions in C with ;.
Well the second possible solution you wrote is incorrect since the 'result' variable in the if statement has no preassigned value. I would simply go with the first one...
What you are trying to do in your 2nd code is assignment inside expressions, which can't be done in Python.
From the official docs
Note that in Python, unlike C, assignment cannot occur inside expressions. C programmers may grumble about this, but it avoids a common class of problems encountered in C programs: typing = in an expression when == was intended.
also, see:
http://effbot.org/pyfaq/why-can-t-i-use-an-assignment-in-an-expression.htm

What is the difference between a statement and a function in Python?

Edit: The suggested duplicate, does not answer my question, as I am primarily concerned with the difference in Python specifically. The suggested duplicate is far broader than this question.
I have recently started to learn Python. I'm currently reading "Learn Python the Hard Way". I have some ad-hoc programming experience, but am going back to the beginning to learn everything from the ground up this time.
In the book, one of the first lessons concerns print and the author provides various instructions of its use in Python 2.7, e.g.:
print "This is fun."
I found myself wondering what print is technically called here from the programming perspective. Some research found this, PEP-3105
In which case is made to make print a function:
The print statement has long appeared on lists of dubious language
features that are to be removed in Python 3000, such as Guido's
"Python Regrets" presentation 1 . As such, the objective of this PEP
is not new, though it might become much disputed among Python
developers.
So print is a statement in Python 2.7, and a function in Python 3.
But I have been unable to find a straight-forward definition for the difference between a statement and a function. I found this also by the person who invented Python, Guido van Rossum in which he explains why it would be good to make print a function instead of a statement.
From what I have read it appears that a function is some code that takes parameters and returns a value. But isn't print doing this in python 2.7? Isn't it taking in strings and returning a concatenated string?
What is the difference between a statement and a function in Python?
A statement is a syntax construct. A function is an object. There's statements to create functions, like def:
def Spam(): pass
So statements are one of the ways to indicate to Python that you want it to create a function. Other than that, there's really not much relation between them.
A statement in Python is any chunk of code you've written. It's more a theoretical concept than a real thing. If you use the correct syntax when writing your code, your statements will get executed ("evaluated"). If you use the incorrect syntax, your code will throw an error. Most people use "statement" and "expression" interchangeably.
Probably the easiest way to see the difference between a statement and a function is to see some example statements:
5 + 3 # This statement adds two numbers and returns the result
"hello " + "world" # This statement adds to strings and returns the result
my_var # This statement returns the value of a variable named my_var
first_name = "Kevin" # This statement assigns a value to a variable.
num_found += 1 # This statement increases the value of a variable called num_found
print("hello") # This is a statement that calls the print function
class User(BaseClass): # This statement begins a class definition
for player in players: # This statement begins a for-loop
def get_most_recent(language): # This statement begins a function definition
return total_count # This statement says that a function should return a value
import os # A statement that tells Python to look for and load a module named 'os'
# This statement calls a function but all arguments must also be valid expressions.
# In this case, one argument is a function that gets evaluated
mix_two_colors(get_my_favorite_color(), '#000000')
# The following statement spans multiple lines and creates a dictionary
my_profile = {
'username': 'coolguy123'
}
Here is an example of a statement that is invalid:
first+last = 'Billy Billson'
# Throws a Syntax error. Because the plus sign is not allowed to be part of a variable name.
In Python, you tend to put each statement on their own line, except in the case of nested statements. But in other programming languages like C and Java, you could put as many statements on a single line as you wanted as long as they are separated by a colon (;).
In both Python2 and Python3, you can call
print("this is a message")
and it will print the string to standard out. This is because they both have a function defined called print that takes in a string argument and prints it.
Python2 also allowed you to make a statement to print to standard out without calling a function. The syntax of this statement was that it started with the word print and whatever came after was what got printed. In Python3 this is no longer a valid statement.
print "this is a message"
Both function and statement are words that Python understands.
Function needs parenthesis to act on anything (including nothing).
Statement does not.
Hence in Python 3 print is function not statement.
Let us take a funny case. not True and not(True) both work. But type(not) is not function hence not is statement. not(True) works only because Python takes parenthesis also for grouping. Bad design, indeed.
Another difference: (not) fails, (print) does not fail, because a statement has no value while a function has one (for the interpreter, not in the mathematical sense of the image of some antecedent).

Why must a variable be declared a global variable before it gets assigned?

Why do we have to do this:
global x
x = "Hello World!"
When this is more readable:
global x = "Hello World"
Why is this, is there a reason behind it?
The goal of Python is to be as readable as possible. To reach this goal the user must be forced act in a clear defined way - e.g. you must use exactly four spaces. And just like this it defines that the global keyword is a simple statment. This means:
A simple statement is comprised within a single logical line.
Simple Statements
And
Programmer’s note: the global is a directive to the parser. It applies only to code parsed at the same time as the global statement.
The global statement
If you would write this:
global x = 5
You would have two logical operations:
Interpreter please use the global x not a local one
Assign 5 to x
in one line. Also it would seem like the global only applies to the current line, and not to the whole code block.
TL;TR
It's to force the user to write better readably code, which is splitted to single logical operations.
The document writes that
Names listed in a global statement must not be used in the same code block textually preceding that global statement.
CPython implementation detail: The current implementation does not enforce the latter two restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program.
As for the readability question, I think the second one seems like a C statement. Also it not syntactically correct
I like to think it puts your focus squarely on the fact that you are using globals, always a questionable practice in software engineering.
Python definitely isn't about representing a problem solution in the most compact way. Next you'll be saying that we should only indent one space, or use tabs! ;-)

Why does python print even if I don't type print?

print "a"; "b"
Will output:
"a"
'b'
Simply typing an int or string into the console will cause it to print.
1
Will output:
1
Is there a reason or benefit for this?
The interactive Python interpreter is a REPL:
a simple, interactive computer programming environment that takes single user inputs (i.e. single expressions), evaluates them, and returns the result to the user
What you are seeing is the return value for each statement. Consider a slightly less simple example where the return value is different from the input:
>>> 2 + 3
5
The tight feedback loop provided by a REPL can be especially helpful when exploring a new language or problem domain.

Assignment within expression in Python

In Java, if I want to increase a variable A, and set B equal to C, I can do it one statement as follows:
B = C + A - A++;
Python, unfortunately, does not support assignment within literals. What is the best way to mimic this kind of behavior within the language of Python? (with the intention of writing code in as few statements as possible)
Let me set something straight: I am not interested in writing code that is readable. I am interested in writing code with as few statements as possible.
One trivial example of one case where this would work would be to write a class that holds an int and has methods such as plus_equals, increment, etc.
In the global namespace, you can do something really ugly like this:
B = globals().__setitem__('A', A + 1) or C
Unfortunately for you (and probably fortunately for the person who has to read the code after you've written it), there is no analogous way to do this with a local variable A.
Let me set something straight: I am not interested in writing code that is readable. I am interested in writing code with as few statements as possible.
Well, if that's your goal, wrap your entire program in a giant exec:
exec """
<your program here>
"""
Bam, one statement.

Categories

Resources