Checking if x>y without if statement
In Python, is it 开发者_StackOverflow中文版possible to check whether x>y without using the if statement?
There are a variety of ways to go about this:
print "yes" if x > y else "no"
or:
print ["no", "yes"][x > y]
or:
print x > y and "yes" or "no"
(at least, this is what my mind-reading powers think that you're doing)
>>> x=1
>>> y=2
>>> "YNEOS"[x<y::2]
'NO'
>>> x=3
>>> "YNEOS"[x<y::2]
'YES'
Yes:
x > y
This returns true if x is larger than y, and there is no if statement involved.
The question is really vague. You could check if x is greater than y in a while loop, or you could use the expression to return a boolean or whatever.
It would be a lot easier to answer if you gave us an example of what you're trying to achieve.
This question is awful, but I suppose I'll contribute an answer anyway:
bool(x>y)
x*(x>y) + y*(x<y)
this will return the greater of x,y
you can try
x > y
or
bool(x>y)
in the second case bool are unecessary, in two codes true or false are returned, however, no checks by the return are performed, and this is your question. NOT, a if statement have a identical translation in hardware and to perform an test (if) in hardware you realy need to use if or an most high level statment
This Answer comes late. If u just want to return anything u can do it with a while loop. Following Example:
while x > y:
# Do anything.
break
Or if u dont want to return u can use break in the Loop After u did what every u want to do. Sorry for my Bad English, i still hope this Answer helped anyway.
精彩评论