getting syntax error with <= sign - python

When using this code:
while str.find(target,key,n) != -1 and <= len(target):
I get a syntax error on 'less than or equal to sign'. Why?

In English we can say "if X is not equal to Y and also less than Z", but Python syntax doesn't work that way.
If you want to compare a number to two other numbers, you have to repeat the original number in the second comparison.
i.e., instead of this:
if x != y and < z:
you must do this:
if x != y and x < z:

If you want to use the double operand, you could rewrite it like:
if -1 < target.find(key, n) < len(target):
pass
But that said, I don’t think find can ever return a value larger than the length of target.

Related

two numerical comparisons in one expression python

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.

Python: How to express less or equal, equal greater, environment?

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?.

Python: Coordinate Conversion

I have a slice of a set of lists of coordinates a[:,4]. It is in astronomical coordinates, which I'd like to convert to decimal. However, it currently doesn't work for negative astronomical coordinates. I currently have:
if any(a[:,4] < 0 ):
b[:,1] = a[:,4] - a[:,5]/60 - a[:,6]/3600 - a[:,7]/360000
else:
b[:,1] = a[:,4] + a[:,5]/60 + a[:,6]/3600 + a[:,7]/360000
print b
The aim of this is to get it to identify if the coordinate is negative or not from the a[:,4] coordinate and then process the other coordinates one way if it is negative, and the other way if it is positive. However, the "if any" line doesn't appear to be working.
For example, -09:24:40.25 should convert to -9.41118, but it currently converts to -8.58882, as the negative "hours" coordinate is then having the arcminute, arcsecond and milliarcsecond coordinates added to it, instead of them being subtracted.
I'm not sure what I'm doing wrong.
Thanks!
You can't use the any function like that assuming you're using a python list, as it takes an iterable and returns true if ANY of that iterable is true
a < 0
won't return an iterable
replace it with
[i < 0 for i in a[:,4]]
or
map(lambda x: x < 0 ,a[:,4])
so that the if statement becomes
if any(map(lambda x: x < 0,a[:,4])):
or
if any([i < 0 for i in a[:,4]])

Finding a value in a range

def shazday(y):
if y >= 1200 or <= 1299:
x = 4
I keep getting syntax on the "=" just before 1299, any idea what I'm doing wrong? I'm trying to find any value between these two numbers to assign a variable. I've tried range itself as well but couldn't get it to work. If I could just find out how to properly check for a value in a range in Python, that would be great.
if y >= 1200 or y <= 1299:
But you probably mean:
if 1200 <= y <= 1299:
Look at it this way, in the if statement you want to evaluate several conditions. So we break it down
if y >= 1200 or <= 1299:
Is y >= 1200? Let's say yes.
if true or <= 1299
Next we ask is... wait a minute? There's nothing there to compare to! (blank) <= 1299 and the system has no idea what (blank) is supposed to be, so it yells at you until you give it something. In this case we have to tell it to check y
if y >= 1200 or y <= 1299:
^
Another way to form this is below, still satisfying that each comparison has something to compare to
if 1200 <= y <= 1299:
# this can be thought of as below
if 1200 <= y and
y <= 1299:
def shazday(y):
if y >= 1200 or y <= 1299:
x = 4
Note the y before the second <=. While y is greater equal or smaller equal is valid in the English language and everybody understands the meaning, this does not work for programming languages...
What the interpreter does is something like
(y >= 1200) is it true or false?
(y <= 1299) is it true or false?
...and then applies the logical operator or. If the second y is missing, the compiler does not know what actually should be smaller equal 1299.
Edit:
Besides the missing y you may also change or to and. Otherwise, the condition will always be true because every number is >= 1200 or >=1299.

integer part of the root withot using functions

The calculation of the integer part of the square root of a number can be done by trial and error, starting from 1, by executing the square until the result is less than or equal to the starting value of which is calculated by the root.
The following program returns the integer part of the root
def radice(x):
z = 0
t = 0
while True:
t = z*z
if t > x:
z -= 1
return z
z += 1
radice(17) // 4
Will be possible to write it without using functions and break?
Here is my code witout function but I dont' know how to write the same algo with no break
z = 0
t = 0
while True:
t = z*z
if t > x:
z -= 1
break
z += 1
print 'The integer part of the root is: ', z
This should suffice:
>>> int(17**0.5)
4
17**0.5 generates the square root of 17, and int basically removes the decimals, leaving you with the "integer part of the root".
Without using any functions, and if you want an integer result, complex code (like your own) is needed. However, if a float will do, then you could try this:
>>> (17**0.5)//1
4.0
This essentially does the same as the int call, but will return a float if either side is a float.
As you said the integer part of the square root of a number can be done by trial and error, starting from 1, by executing the square until the result is less than or equal to the starting value of which is calculated by the root.
Said that you can write the code without using function and break statements; here is the code:
n = input("insert a number: ")
r = 1
while (r * r <= n):
r = r + 1
print "the result is:", r -1
Parens are for clarity, not required
>>> (17**.5)-(17**.5)%1
4.0
Ok, let's think logically.
You cannot use break, so the only way to get out of the while loop is to break its condition.
If it's True, it cannot be broken, so we have to think about the proper condition to stop iterating. And this condition is already used in your algorithm: you exit when t > x, or z * z > x. So the condition to continue iteration should be the opposite, i.e. z * z <= x. And we have this simple solution.
x = 17
z = 0
while z * z <= x:
z += 1
print 'The integer part of the root is: ', z - 1
As a general rule, try to shy away from those while True: loops. While they are sometimes useful, they're generally harder to read and understand, this is probably why your teacher limits the use of break. The function was prohibited probably because return is just another way of escaping the loop. But those are exceptional: the normal way to end a loop is to break its condition, so this is how it should be written.

Categories