Python: what does d = _ mean? [duplicate] - python

This question already has an answer here:
What is the purpose of the single underscore “_” variable in Python?
4 answers
At 44:05 in his Fun of Reinvention talk, Dave Beasley writes
>>> d = _
There is a lot before that, which is necessary for the result he gets. But ignoring the output, what does that input line mean? Whenever I try it, either in a file in the PyCharm editor, in the PyCharm Python console, using straight IDLE (all v3.7) I get an error.
Any idea what this may mean and how to get something like that to run?

_ is a special variable in the python language.
In some REPLs, like IDLE, it holds the result of the last expression executed.
d = _ assigns the result of the last expression executed to d.


Python: What does this mean in raw_input function? [closed]

So, I recently started learning python and I am in the raw_input() section.
So while I was trying out different things, I made an error (at least that's what I think for now). Can someone please explain what is the difference between the two statements?
var1 = int(raw_input())
var1 = int((raw_input())
I know that the first one waits for an input from the user and assigns it to the variable var1 but, in the second case, this is the output I am getting.
>>> x = int((raw_input()) On pressing enter, it just shows the ellipses and waits for a user input.
... 12 Twelve was my input and then I get the following error.
File "<stdin>", line 2
SyntaxError: invalid syntax
I know it clearly says it is a Syntax Error but shouldn't it even accept the statement? Why does it wait for an in input?
Thank you.
Python Version: 2.7
OS: Windows
var1 = int((raw_input()) has three left parentheses and two right ones. Until you complete the expression with another right parentheses, Python thinks you have not finished writing the expression. That is why it shows an ellipsis.
When you type "12", the full expression becomes var1 = int((raw_input())12, which is not valid syntax because you can't have a number immediately after a closing paren.
Expanding on Kevin's answer, here's why you would want Python to behave like this. In this case it provides you with a rather confusing error, but if you did something like
>>> x = int((raw_input())
... + "123")
then it could be parsed as
>>> x = int((raw_input()) + "123")
>>> x = int(raw_input() + "123")
which would be a valid expression. This becomes useful when you want to write very long expressions which don't fit on one line. Any time you have an extra open parenthesis you can continue the expression on a new line. One case you might want to do this is:
if (check_a_condition(a) and check_a_condition(b) or
check_a_condition(c) and check_a_condition(d)):

How turn invalid character identifier into valid

I'm trying do the follow sentence:
¬ = lambda x: not x
but I'm getting the follow error:
File "<stdin>", line 1
¬ = lambda x: not x
SyntaxError: invalid character in identifier
Ok, I know that is an invalid sentence in Python, but I'm looking for a solution that allows me to use this syntax.
My target is create a script to run Propositional Logic Easily, and if I can do it, I'm be able to do some things with sugar syntax like as below:
¬ False
Short of rewriting the parser (which isn't a good idea), this is impossible in Python. Variable names may only contain letters, digits, and/or underscores. Additionally, the first character must be either a letter or an underscore. Also, a variable name cannot be the same as a keyword such as if or class.
Other than that, there can be no other characters in the name. You likewise cannot make your own keywords or operator symbols (although you can overload most of the existing operators on a custom class to do whatever you want. Here is a reference: operator overloading in python).
For more information, here is a link to Python's grammar specification and one which defines identifiers and keywords in Python.
Also, just for the record, you could use operator.not_ instead of making your own function to invert booleans.
Thanks a lot for the help, the #iCodez has answered perfectly to python context, but in true I am opened to use others languages who can do it, and I found it on Ruby, below the ruby code that runs what I want:
# coding: utf-8
σ = 9
def √(x)
def ¬(x)
not x
puts σ
puts √ σ
puts ¬ false
and the output:
thanks again for help! And thanks too to the programmers thread that help-me to find other languages.

Python assignment to variable

I have some code in python like:
something = r"grep some {0} stuff".format("somethingelse")
r = subprocess.check_output(
something, shell=True, cwd=os.path.join(directory, 'path'))
In essence, I want to know what the first assignment is doing with "r". If "r" has a value (assigned last), how is the first assignment able to use it successfully (r doesn't have a value yet)? What exact does the first line do when it uses "r"?
I know you guys will hate this question, but it's something that's very difficult to google for. Feel free to throw me a link to read and I'll be on my way.
Also, if I do:
test = r"wat"
in a completely separate script, the command will work. Then when you print "test", all it does it print "wat". What happens to the "r"?
Putting r before a string literal designates it as a raw string literal, meaning that escape sequences are not processed (a backslash \ is just a backslash). It has nothing to do with the variable r that you use in the second line of your example.

What does the underscore represent in Python?

I am kind of new to Python, so I am trying to read over existing code. I am a little confused on the syntax of this though.
For example:
rlist, _, _ =, [], [])
I understand that takes 3 lists (and I assume [] just means empty list), but is the _ used to denote a placeholder of some sort?
It's just the name of a variable! Usually people use _ for variables that are temporary or insignificant.
As other people have stated, _ is a common alias for gettext, a translation library. You can identify when it's being used as gettext if you see it called as a function, eg. _('Hello, world!').
Protip: In the python console it can be used to retrieve the result of the last statement.
>>> 3 + 4
>>> a = _
>>> print a
It's just an anonymous variable, and has no special meaning to python. Compare it with using i as a loop counter.
You generally use it to document that the surrounding code is going to ignore the value of that variable.
In the python interactive console, the result of the last expression is assigned to _, but that does not carry through in python programs.
Despite what the other answers say, _ does have a special meaning in Python. It's the last result printed at the interactive prompt.
>>> 2+2
>>> _+2
(Of course if there is no interactive prompt, e.g., because you're running a Python script from the shell, then it doesn't have a special meaning.)
It represents an anonymous variable. It's used because the variable is required but the value can be ignored.
Generally, you name a variable with a single underscore when you never need to refer to the variable again. For example, something like this:
for _ in range(10):
print "hello"
This just prints "hello" 10 times, and we never need to refer to the loop control variable (_ in this case).
In your example,, [], []) returns a tuple (or list or set) from which you seemingly only need the first item, hence you the use of the underscores.

Invalid syntax error in Python

I'm starting Comp Sci courses in Uni this coming fall (starting with zero programming knowledge), so I'm just starting to play around programming. I'm following a book and tried copy-pasting some code - but it doesn't work. Here's what I tried:
>>> def function(x):
return x+2
SyntaxError: invalid syntax
The word "function" was highlighted. I'm confused because the very same example is used in the book and it appears to work but then I get that error on my end. What's going on here?
You need to separate the function definition from its execution. Also, Python is sensitive to whitespace at the beginning of lines. Try this (exactly):
def function(x):
return x+2
or, in one line (which you should not do; see the style guidelines):
def function(x): return x+2; function(2)
or, in the Python shell:
>>> def function(x):
return x+2
>>> function(2)
Note the blank line between the function definition and its use. After you define the function, hit enter once to get the prompt back.
I'm assuming you meant to put Python in the title. Python has interesting syntax rules in that it actually counts white space as meaningful when parsing the program. What I mean is that having extra space, newlines, or tabs, etc. actually changes the meaning of the program. Double check the book example and make sure you have the exact same (tabs, new lines, and all) syntax written. It may look closer to this:
def f(x):
return x + 2
note the new line and tab. To call this function, on a separate line say:
or replace 5 with whatever parameter you want.
so the full script should be:
def f(x):
return x + 2
Try this:
def function(x):
return x+2
In python, indentations are important. They are the {} of the python world.
You actually do not need to add extra whitespace before function(5) because python knows not to include it in the function definition because it is not indented. It is still good practice to add the extra blank line, but it is not strictly necessary.
This is for the users using Python 2.6.6 and IDLE 2.6.6.
Since Python interpreter is very much sensitive to whitespace and indentations, we need to separate the function declaration from the execution.
What you must be doing:
>>> def square(input):
return output
print square(5)
Output: SyntaxError: invalid syntax
Correct way to do it:
>>> def square(input):
return output
>>> print square(3)