Simple python conditional statement shortcut syntax [closed] - python

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am having trouble understanding the shorthand conditional statement in the python below.
def number(number):
return number or number == 3
print number("")
What does this shortcut syntax mean? Is it the same as the following?
def number(number):
if number or number == 3:
return number
print number("")
The first prints False and the latter None (I believe None means the syntax is not valid?).

The conditional statement is a bit pointless in this case (except for some very strange cases like overwriting the equals/integer/boolean values of number).
Basically what you are doing right now is like this:
def number(number):
if number:
return number
else:
return number == 3
If there would be an and it would be useful, right now it's pointless.
The or can be useful like this:
return spam or eggs
If spam is not null it will return spam, otherwise it will return eggs.
Illustration btw:
>>> for number in range(5):
... print 'number', number, number or number == 3
number 0 False
number 1 1
number 2 2
number 3 3
number 4 4
Long version of number and number == 3 or 5
def number(number):
if number and number == 3:
return 3
else:
return 5
The spam and spam.eggs thing is useful because if spam would be None it wouldn't execute the spam.eggs part which would normally give an AttributeError.

The relevant expression in both cases is number or number == 3.
Python splits this expression into 2 parts: (number) or (number == 3)
It evaluates the individual parts first, and then evaluates the results with or.
So we have "" (treated as False) or "" == 3 (which evaluates to False).
This becomes "" or False. Since both expressions are False-y, this entire expression evaluates to False.
In the first function, you return the value of the expression, which is False.
In the second function, you only return the value of the expression if it is true. If it's false, you don't return anything.
In python, a function which doesn't return anything returns None by default.

If number is valued to True (So, not 0 or None), the function just returns the number.
If the number is valued to False, the function will return number == 3 (So True if it's 3, False else)
As the latter will always return False (If number == 3, then the function would have returned 3 in the first case), it could be shortened down to:
return number or False
Which will return the number if it's not 0 or None, else it will return False.

It has to do with how Python evaluates expressions and objects.
Your first example:
You send in a empty string "", this to Python is False, much like an empty list ([]).
def number(number):
# so this will now be (False) or (number == 3) but since the first
# expression was False it will not evaluate the number comparison and thusly
# return False
return number or number == 3
print number("")
Your second example is a otherwise.
You have an explicit if stating that if numbers evaluate to True ie. not empty or numbers are equal to 3 enter the following block and return from it.
But since you supply an empty string, which we just learned returns False, it will by pass the if and return the default value for any Python function, None.
def number(number):
if number or number == 3:
return number
#default says return None here.
print number("")

Related

Explain this if-else condition in Python

Code
def addition(num):
if num:
return num + addition(num - 1)
else:
return 0
res = addition(10)
print(res)
Explanation
I know what the function is doing:
it is a recursive function
I just don't know what if num: means or the else part.
I am guessing it means as long as the num is int do what is inside the if, else return 0.
Question
Can someone tell me what this code means?
if variable: and truthyiness
See the boolean values and Python's Truth Value Testing:
What is Truthy and Falsy? How is it different from True and False?
You can evaluate truthy and falsy values using the bool() conversion-function:
print('None:', bool(None))
print('zero:', bool(0))
print('negative:', bool(-1))
print('positive:', bool(1))
if num: mets if num is defined and unequal to 0:
is defined: num is not None
and is not zero: num != 0
bool(0) is False. The opposite condition is tested by if not num.
The role of if in a recursive function
It's a recursive function which calls itself until exit-condition num == 0 is met in the else branch. Then it simply returns 0. So, the role of if num: is the continue-condition opposed to an exit-condition.
You could also write it as exit-condition:
def addition(num):
if not num: # equivalent to: if num == 0 or num is None
return 0 # return 0 if exit-condition met
# default behavior: recurse until zero met
return num + addition(num - 1)
See also:
recursive factorial function
Basics of recursion in Python
Edge-cases for input
Note, how input of None and other falsy values return a zero.
Please also consider the edge-case of negative input, as Fred commented. Could (silently) return 0 to abort addition. Also might raise an error to warn about misuse, like:
if num < 0:
raise ValueError("Can not calculate the recursive-sum for negative values.")
What happens if a float like 10.5 is given as input?
It would step through each -1 decrease until 0.5. The next call of addition(-0.5) would jump over the num == 0 exit-condition and cause infinite recursion, even a stackoverflow.
Python and many other languages have a concept of "falsy", which roughly means "values that are treated as False when evaluated as a boolean". In Python, values that are falsy include empty collections such as empty lists, strings, sets, tuples, and dicts, the int or float 0, and None. I may be missing some here, and you may find that some classes are designed to be treated as falsy as well under certain conditions. There are also "truthy" values which evaluate to True is a boolean context. It's easy to find out if a value is truthy or falsy. Simply call bool() on it:
bool(0.0)
# False
In the context of your code, when 0 is reached, that will be evaluated as falsy, triggering the exit condition.
if num: means if num is different than 0 : if num!=0.
you better remove the else statement.
def addition(num): if num: return num + addition(num - 1) return 0
python already knows that return is an else statement.
here's a playlist of one of the bests on youtube by corey to learn & become at python : https://www.youtube.com/watch?v=YYXdXT2l-Gg&list=PL-osiE80TeTskrapNbzXhwoFUiLCjGgY7
and also I recommend this book, automating the boring stuff with python. it's free : https://automatetheboringstuff.com/

How does this if statement determine whether num%2 is true or false [duplicate]

This question already has answers here:
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
Closed 2 years ago.
Okay, so here is a piece of code. The function of the code is to take a value and determine whether or not it is odd or even.
def isEvenOrOdd(num):
return 'odd' if num % 2 else 'even'
Now my question lies in why this works. The way I am currently looking at this, is that --
num%2 returns a value. If num is 3, then num%2 = 1.
Why would the value of '1' satisfy the 'if' condition?
I assumed this was a matter of 1 and 0, but I tried the same code with %4, and if 3 is returned, it still satisfies the if statement.
I understand this may be a basic question for some, so my apologies for perhaps being slow in understanding this. Thank you!
Thank you for your help ! I actually understand it now
The reason has to do with the "truthy-ness" of objects in Python. Every object in Python, even if it's not a boolean value, is considered "truthy" or "falsy". In this case, an integer is considered "truthy" if and only if it is not zero.
Therefore, if the number is odd, its modulus will be 1 which is considered true. Otherwise, the modulus will be 0 which is considered false.
If you switch the modulus to 4, the result will be truthy iff the remainder is not zero (i.e., if the number isn't a multiple of 4).
in python the, some data types has a true value or a false value, it doesn't have to be a boolean.
for example
test = None
if test:
print("working")
else:
print("Not working")
you will notice you get an ouput of Not working the reason is for object None is regarded as False same applies for some other data type , for integer, as long as a value is zero (0) it will take it as False
So in your case, if num % 2 return 0 then you will have
'odd' if 0 else 'even' # will will return 'even'

Is this recursion is posible?

Can someone please explain to me how this piece of recursive code is working? Because there is only one if statement which checks if variable x is equal to zero and returns true if the value is equal to zero.
And the other part is just upon calling each other.
def is_even(x):
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
return not is_even(x)
print(is_odd(17)) # outputs true
print(is_even(23)) # outputs false
This pair of mutually recursive functions makes use of three facts:
0 is even
x is even if x - 1 is odd.
x is odd if x - 1 is even.
1 is odd because 1 - 1 == 0 is even.
2 is even because 2 - 1 == 1 is odd.
And so on.
This is not an efficient way to determine if an arbitrary value n is even or odd, but it is a logically correct way. (Assuming the argument is always a natural number, anyway. Passing a negative integer as an argument to either results in infinite recursion, as the base case will never be reached.)
I want to give a simpler answer to follow along with. Think about the stack trace. I'll abbreviate is_even and is_odd as IE and IO respectively.
IO(17)
NOT[IE(17)]
NOT[IO(16)]
NOT[NOT[IE(16)] = IE[16]
IO(15)
...
This is basically checking if alternating descending numbers starting from the input value are even and odd all the way down to 0. Note that if we start with a true statement (like IO(17)) then every line contains a true statement - if we started with a false statement, every line ends up with a false statement. Following the pattern we see here, we see that the final state can therefore end up as
IE(1) -> IO(0) -> NOT[IE(0)] = NOT[True] = False # as expected!
OR
IO(1) -> NOT[IE[1]] = NOT[IO[0]] = NOT[NOT[IE(0)] = NOT[NOT[True]] = True # likewise!

How to use 'while 'variable':'

I'm new to python and was looking around for a code for a function where the user inputs and integer and the function adds and returns the sum of the digits of the number.
The code looked like this:
def sum_digits(n):
s = 0
while n:
s += n % 10
n //= 10
return s
So I know how a while loop works, but I can't wrap my head around (nor am able to find anything on Google) about how this works. I thought While loops always have a condition such as 'while n<10' or the sort.
What exactly is 'while n:' saying? How does this code work exactly? How does the code know how to stop running, and how exactly does it even return the sum of the digits (all I see it doing is returning the remainder of s/n).
Thanks for the help and sorry for any stupid questions.
while implicitly calls bool on the argument. So as long as bool(n) in your example is True the while loop continues.
And Pythons documentation for builtin types states that any number except zero is considered True:
By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. Here are most of the built-in objects considered false:
constants defined to be false: None and False.
zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
empty sequences and collections: '', (), [], {}, set(), range(0)
So basically the while n loop will continue until n becomes zero (or you break or return or raise...)
while n: is equivalent to while n!=0: (in this case, when you're dealing with numbers). Since each value in python has a Boolean value, for any number that is different from zero, bool(n) == True, if n equals zero, bool(n) == False.
That function can be written like (Thanks to #Jean-FrançoisFabre for suggesting the use of divmod):
def sum_digits(n):
s = 0
while n != 0:
n, t = divmod(n, 10) # to not use division and modulo separately
# n has the value of n//10, t has the value of n%10
s += t
return s
print(sum_digits(154)) # => 10
print(sum_digits(134)) # => 8
print(sum_digits(987)) # => 24

Using IF, AND, OR together with EQUAL operand together in Python [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
I'm trying to create a function where the given value (passed as a string) is checked to see if the number of digits is either 4 or 6, and that it is a number.
My first impulse was to go with this code:
def number(x):
if (len(x) == (4 or 6)) and x.isdigit():
print "True"
else:
print "False"
This code above only passes the first test below...I don't understand why it passes this but none of the other tests:
number("1234")
Only when I separate out the len() functions will it work properly.
def number(x):
if (len(x) == 4 or len(x) == 6) and x.isdigit():
print "True"
else:
print "False"
## Checks
number("1234")
number("123456")
number("abcd")
number("abcdef")
number("1")
number("a")
The above code passes all tests.
So my questions are:
What's going on here?
Any way to write cleaner code for this?
Thank for the help!
** Not a duplicate question because although this question has the same underlying concepts regarding boolean operators, the problem itself is different due to the usage of len(), isdigit(), and the additional question of how best to improve it (someone commented the usage of return). Definitely adds another perspective to the other question though.
It helps to examine the logic of this line:
if (len(x) == (4 or 6)):
The (4 or 6) clause contains a logical or short circuit. The value 4 is true, so it is evaluated and returned to the == relational comparison.
The way that or works is that its lefthand side is evaluated for Boolean truth, and its value is returned if true. If the lefthand side is not Boolean true, then the righthand side is evaluated and its value is returned.
Because the lefthand side of the 4 or ... is true in a Boolean sense, the righthand side is never evaluated. Python doesn't even look past 4 or. If the left-hand value were a false value (such as 0), then the right hand side of the or would be evaluated.
To see this in action, try print 4 or 6. The output will be 4.
So since the 4 is a hard-coded true value, your comparison is semantically the same as if (len(x) == 4) -- that is, since 4 is true, 6 is never evaluated.
What I suppose you really want to know is if len(x) is either 4 or 6. You could put that to code in a couple of ways:
if(len(x) == 4 or len(x) == 6 ...
if(len(x) in (4,6) ...
You can use the in operator like so:
def number(x):
if len(x) in (4, 6) and x.isdigit():
print "True"
else:
print "False"
where in checks for containment in a given container. Note that 4 or 6 on their own evaluate to something undesirable, which is why your first code segment fails. You can check it out on the python shell:
>>> 4 or 6
4
You probably wanted to write
if (len(x) in (4, 6)) and x.isdigit():
Instead of
if (len(x) == (4 or 6)) and x.isdigit():
Short answer: len(x) in [4, 6] or len(x) == 4 or len(x) == 6.
"or" is a boolean, or logical choice. (4 or 6) is guaranteed to resolve to a non-zero (true) value. In this case, it resolves to 4, so your test case passes.
I'll go ahead and answer
Any way to write cleaner code for this?
Yes. Return the boolean value, rather than printing a string.
def number(x):
return len(x) in {4, 6} and x.isdigit()
print(number("1234")) # True
Then, it is simple do use your method in a if-statement without string comparison.
The trouble is in your or statement.
Any value greater than one will evaluate to True when you put it in a conditional. So (4 or 6) will always resolve to true.
You could use the in statement above or you could just use two =='s:
if (len(x) == 4 or len(x) == 6) and x.isdigit()
It's a bit wordier, I find it easier to read.

Categories

Resources