Reputation:
is there a way to test multiple variables within the same range (x1,y1,x2,y2 in range...)?
I would like the code to be shorter after the if
mouv="7647"
x1,y1,x2,y2=int(mouv[0]),int(mouv[1]),int(mouv[2]),int(mouv[3])
if len(mouv)==4 and x1 in range(8) and y1 in range(8) and x2 in range(8) and y2 in range(8):
print("code ok")
Upvotes: 1
Views: 73
Reputation:
Here is a way using all
:
mouv = "7647"
# I cleaned this up too
x1,y1,x2,y2 = map(int, mouv[:4])
if len(mouv)==4 and all(z in range(8) for z in (x1, y1, x2, y2)):
print("code ok")
Note that if your range is huge, you should use Python's mathematical operators instead:
if len(mouv)==4 and all(-1 < z < 8 for z in (x1, y1, x2, y2)):
With large ranges, using mathematical operators is faster than doing x in range(n)
. With small ranges however, the difference is negligible.
Upvotes: 1
Reputation: 251136
Use all
:
if len(muov) == 4 and all(int(x) in range(8) for x in mouv)
Or if range
is huge then it's better to use chained comparison operators as range
creates a list in memory and is slow compared to simple mathematical comparisons:
if len(muov) == 4 and all(0 <= int(x) < 8 for x in mouv)
Upvotes: 2