I'm trying to use in Python 3.3 an old library (dating from 2003!). When I import it, Python throws me an error because there are <> signs in the source file, e.g.:
if (cnum < 1000 and nnum <> 1000 and ntext[-1] <> "s":
...
I guess it's a now-abandoned sign in the language.
What exactly does it mean, and which (more recent) sign should I replace it with?
It means not equal to. It was taken from ABC (python's predecessor) see here:
x < y, x <= y, x >= y, x > y, x = y, x <> y, 0 <= d < 10
Order tests (<> means 'not equals')
I believe ABC took it from Pascal, a language Guido began programming with.
It has now been removed in Python 3. Use != instead. If you are CRAZY you can scrap != and allow only <> in Py3K using this easter egg:
>>> from __future__ import barry_as_FLUFL
>>> 1 != 2
File "<stdin>", line 1
1 != 2
^
SyntaxError: with Barry as BDFL, use '<>' instead of '!='
>>> 1 <> 2
True
It means NOT EQUAL, but it is deprecated, use != instead.
It's worth knowing that you can use Python itself to find documentation, even for punctuation mark operators that Google can't cope with.
>>> help("<>")
Comparisons
Unlike C, all comparison operations in Python have the same priority,
which is lower than that of any arithmetic, shifting or bitwise
operation. Also unlike C, expressions like a < b < c have the
interpretation that is conventional in mathematics:
Comparisons yield boolean values: True or False.
Comparisons can be chained arbitrarily, e.g., x < y <= z is
equivalent to x < y and y <= z, except that y is evaluated
only once (but in both cases z is not evaluated at all when x <
y is found to be false).
The forms <> and != are equivalent; for consistency with C,
!= is preferred; where != is mentioned below <> is also
accepted. The <> spelling is considered obsolescent.
See http://docs.python.org/2/reference/expressions.html#not-in
It is an old way of specifying !=, that was removed in Python 3. A library old enough to use it likely runs into various other incompatibilities with Python 3 as well: it is probably a good idea to run it through 2to3, which automatically changes this, among many other things.
Use != or <>. Both stands for not equal.
[Reference: Python language reference]
The comparison operators <> and != are alternate spellings of the same operator. != is the preferred spelling; <> is obsolescent.
Related
I thought I read somewhere that python (3.x at least) is smart enough to handle this:
x = 1.01
if 1 < x < 0:
print('out of range!')
However it is not working for me.
I know I can use this instead:
if ((x > 1) | (x < 0)):
print('out of range!')
... but is it possible to fix the version above?
It works well, it is your expression that is always False; try this one instead:
x = .99
if 1 > x > 0:
print('out of range!')
Python chained comparisons work like mathematical notation. In math, "0 < x < 1" means that x is greater than 0 and less than one, and "1 < x < 0" means that x is greater than 1 and less than 0.
And. Not or. Both conditions need to hold.
If you want an "or" , you can write one yourself. It's or in Python, not |; | is bitwise OR.
if x > 1 or x < 0:
whatever()
Alternatively, you can write your expression in terms of "and":
if not (0 <= x <= 1):
whatever()
You can do it in one compound expression, as you've already noted, and others have commented. You cannot do it in an expression with an implied conjunction (and / or), as you're trying to do with 1 < x < 0. Your expression requires an or conjunction, but Python's implied operation in this case is and.
Therefore, to get what you want, you have to reverse your conditional branches and apply deMorgan's laws:
if not(0 <= x <= 1):
print('out of range!')
Now you have the implied and operation, and you get the control flow you wanted.
I want to do the following example in python:
x = 10
y = 8
if x-5 <= y <= x+5:
print(y)
I see that this is working, but I would like to know if it's "ok" like this, if there is a better solution or something I have to consider doing it like this.
Chained expressions are acceptable in Python:
Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent
to x < y and y <= z, except that y is evaluated only once (but in both
cases z is not evaluated at all when x < y is found to be False).
In fact, because and is lazy and the syntax is cleaner, they are preferable.
Just be aware that chained expressions take priority. For example, see Why does the expression 0 < 0 == 0 return False in Python?.
Some if and else's can be rewritten1 and shortened2 (codegolf-style) likewise, because booleans can act as integers in Python. For example if a<b:return a can be rewritten3 as return("",a)[a<b].
In this case (I simplified the condition for readability),
if a<b: print(a)
can be rewritten as both of the following:
print(("",a)[a<b])
(print(""),print(a))[a<b]
(if we ignore newlines, else end="" can be used).
I would like to decrement a variable n (the whole thing is in a while loop with n in its condition) when a<b is true on top of everything, eg.
if a<b:
print(a)
n-=1
while using the syntax trick above.
In C, (n/n--)-1 is not only equal to 0, but also substracts 1 from n. In Python, I haven't found a way to do this. Some invalid syntaxes I tried:
print(("",a+(n/n--)-1)[a<b])
(print(""),(print(a);n-=1))[a<b]
How to decrement the variable (and print a) when the condition is true using this "trick"?
1,2,3: these statements aren't always true
Python isn't C. For one thing, Python doesn't have a decrement operator, so print(n--) won't work. For another, assignments in Python are statements, not expressions, so print(n-=1) won't work.
If you truly wanted your print statement to have side effects, it could invoke a function:
def decrement():
global n
n -= 1
return n
print(decrement())
But don't. No one will expect that your print statement has side-effects, so everyone will be surprised when commenting out your print statement changes the program's result.
EDIT: I just noticed that this is a code golf question. In that case, my stylistic advice isn't really valid. Everyone expects golfed code to be weird.
Ps. If your goal is to change if statements into expressions, then play with and and or, which short circuit. For example:
a<b and (print(a), decrement())
Or use if ... else expressions
(print(a),decrement()) if a<b else None
n = 10
print(n // (n := n-1) - 1)
# (x := y) is the equivalent of x = y
#but you can use it inside expressions
#and it returns the new value of x
# finally a C simple assignment
a = (b := 1)
print(a, b)
gives
0
1 1
What does the := operand mean, more specifically for Python?
Can someone explain how to read this snippet of code?
node := root, cost = 0
frontier := priority queue containing node only
explored := empty set
Updated answer
In the context of the question, we are dealing with pseudocode, but starting in Python 3.8, := is actually a valid operator that allows for assignment of variables within expressions:
# Handle a matched regex
if (match := pattern.search(data)) is not None:
# Do something with match
# A loop that can't be trivially rewritten using 2-arg iter()
while chunk := file.read(8192):
process(chunk)
# Reuse a value that's expensive to compute
[y := f(x), y**2, y**3]
# Share a subexpression between a comprehension filter clause and its output
filtered_data = [y for x in data if (y := f(x)) is not None]
See PEP 572 for more details.
Original Answer
What you have found is pseudocode
Pseudocode is an informal high-level description of the operating
principle of a computer program or other algorithm.
:= is actually the assignment operator. In Python this is simply =.
To translate this pseudocode into Python you would need to know the data structures being referenced, and a bit more of the algorithm implementation.
Some notes about psuedocode:
:= is the assignment operator or = in Python
= is the equality operator or == in Python
There are certain styles, and your mileage may vary:
Pascal-style
procedure fizzbuzz
For i := 1 to 100 do
set print_number to true;
If i is divisible by 3 then
print "Fizz";
set print_number to false;
If i is divisible by 5 then
print "Buzz";
set print_number to false;
If print_number, print i;
print a newline;
end
C-style
void function fizzbuzz
For (i = 1; i <= 100; i++) {
set print_number to true;
If i is divisible by 3
print "Fizz";
set print_number to false;
If i is divisible by 5
print "Buzz";
set print_number to false;
If print_number, print i;
print a newline;
}
Note the differences in brace usage and assignment operator.
PEP572 proposed support for the := operator in Python to allow variable assignments within expressions.
This syntax is available in Python 3.8.
This symbol := is an assignment operator in Python (mostly called as the Walrus Operator). In a nutshell, the walrus operator compresses our code to make it a little shorter.
Here's a very simple example:
# without walrus
n = 30
if n > 10:
print(f"{n} is greater than 10")
# with walrus
if (n := 30) > 10:
print(f"{n} is greater than 10")
These codes are the same (and outputs the same thing), but as you can see, the version with the walrus operator is compressed in just two lines of code to make things more compact.
Now, why would you use the walrus operator?
First off, don't feel obligated.
I myself even rarely use this one. I'm just using the walrus operator to compress my code a little bit, mostly when I'm working with regular expressions.
You can also find your own use case of this. What's important is you have a rough idea about it and knows when it might be helpful when you encountered a problem like this one.
And this is by far how can I explain walrus operator in a higher level. Hope you learned something.
The code in the question is pseudo-code; there, := represents assignment.
For future visitors, though, the following might be more relevant: the next version of Python (3.8) will gain a new operator, :=, allowing assignment expressions (details, motivating examples, and discussion can be found in PEP 572, which was provisionally accepted in late June 2018).
With this new operator, you can write things like these:
if (m := re.search(pat, s)):
print m.span()
else if (m := re.search(pat2, s):
…
while len(bytes := x.read()) > 0:
… do something with `bytes`
[stripped for l in lines if len(stripped := l.strip()) > 0]
instead of these:
m = re.search(pat, s)
if m:
print m.span()
else:
m = re.search(pat2, s)
if m:
…
while True:
bytes = x.read()
if len(bytes) <= 0:
return
… do something with `bytes`
[l for l in (l.stripped() for l in lines) if len(l) > 0]
Happy 3.8 Release on 14th of October!
There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus.
In this example, the assignment expression helps avoid calling len() twice:
if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")
What’s New In Python 3.8 - Assignment expressions
:= is also called as Walrus Operator.
We can use this walrus operator to assign a value and do condition check at the same time.
Eg:
Without Walrus Operator:
a = 10
if a == 10:
print("yes")
With Walrus Operator:
if (a := 10) == 10:
print("Yes")
So, we can use variable a not just in statement also after that. it will simply assign new value into variable and enables condition check.
PEP 8 discourages the usage of compound statements, but I couldn't find anything about the advised usage of Python's ternary/conditional syntax. For example:
return x if n == 0 else y
i = x if n == 0 else y if n == 1 else z
Does there exist any convention concerning whether the above statements should be preferred to more traditional if/else blocks?
if n == 0:
return x
return y
if n == 0:
i = x
elif n == 1:
i = y
else:
i = z
The "traditional if/else blocks" should generally be preferred.
The only places where you'd still want to use the ternary operator is in places where the syntax requires an expression, e.g. within lambda expressions. Even there, only do it if the ternary expression is short and readable (of course, readability is subjective..)
You can always replace a lambda expression with a small function, but in places where you think that would make the code less readable, it is ok to use lambda expressions with short ternary operations.
I agree with shx2's comments.
Another consideration is testability... using the ternary expr places all the logic on a single line/expr. Basic line-base code coverage tools wouldn't then give a good read on the true coverage of your tests.
Using traditional is/else blocks gives a better reading.