I don't know if this has been asked before but here I go.
A while loop takes a bool, something like while a<5 or while True and proceeds to do something.
n = 10000
count = 0
while n:
count = count + 1
n = n / 10
n=int(n)
print (count)
This code will execute the while loop, but why, I understand that I could use 1 instead of True, but here it's going like "while 10000", and 10000 != True, so how does that work?
Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function bool() can be used to convert any value to a Boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).
Related
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/
I am really confused about this one, I'm sorry if it's a stupid question.
I have a lab question that asks me to write a Boolean expression to test if the number input is in range.
Would this be the correct way to write this expression?:
if 1 <= number <= 10:
True
else:
False
The 1 <= number <= 10 part is the valid expression; something you can evaluate and/or assign to a variable (if itself uses the result of the expression to alter the control flow of the program). You don't need to write True or False at all, since the test itself produces True/False as appropriate; return 1 <= number <= 10 or in_range = 1 <= number <= 10 is more efficient and simpler than equivalent if/else tests that explicitly perform return True/return False or in_range = True/in_range = False.
Another valid (if typically slightly slower) solution (for integers only, since, for example, 4.5 wouldn't pass this test where it would pass the former) would be:
number in range(1, 11)
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
This question already has answers here:
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
Closed 5 years ago.
sum, Nr = 0, 12
i = Nr
while i:
sum += i
i -= 1
print ('The sum of all natural numbers up to (and inclusive of) ' + repr(Nr) +
' is ' + repr(sum))
So this is a very simple while loop in python 3 which returns "The sum of all natural numbers up to (and inclusive of) 12 is 78" as expected.
What I am confused about is that why this condition "while i:" works here when "i" is not subjected to any comparison operator.
Thanks!
In conditional statements, the input is implicitly cast to boolean, hence the loop is equivalent to
while bool(i):
...
bool(i) is True as long as i != 0, and False if i == 0, so the loop goes until i becomes zero.
While expect the expression and if it is true is runs the loop.
while_stmt ::= "while" expression ":" suite
["else" ":" suite]
In [38]: bool(Nr)
Out[38]: True
while loop expects any condition either True or False. When you write while i (suppose i = 5) it is evaluated as True, so the loop continues but when it encounters i=0 it is evaluated as False and the loop breaks.
It seems that Python does an implicit replacement with i not equals zero (pseudo code). See documentation.
Python automatically computes the truthy value of the variable passed to it by converting it into boolean. Since i being a non-zero positive integer is considered true in Python, that's why it's working, till it finally becomes 0 which is considered false.
>>> print(bool(3))
True
>>> print(bool(0))
False
In python, values are duck typed - what this means is that the interpreter can try to fit the value into whatever context you have put it. All numbers other than zero are 'truthy', so for instance
if 3: # True
Whereas zero is falsy:
if 0: # False
I have always thought that using -1 in a condition is alway the same as the writing False (boolean value). But from my code, I get different results:
Using True and False:
def count(sub, s):
count = 0
index = 0
while True:
if string.find(s, sub, index) != False:
count += 1
index = string.find(s, sub, index) + 1
else:
return count
print count('nana', 'banana')
Result: Takes to long for interpreter to respond.
Using 1 and -1:
def count(sub, s):
count = 0
index = 0
while 1:
if string.find(s, sub, index) != -1:
count += 1
index = string.find(s, sub, index) + 1
else:
return count
print count('nana', 'banana')
Result: 1
Why does using -1 and 1 give me the correct result whereas using the bool values True and False do not?
string.find doesn't return a boolean so string.find('banana', 'nana', index) will NEVER return 0 (False) regardless of the value of index.
>>> import string
>>> help(string.find)
Help on function find in module string:
find(s, *args)
find(s, sub [, start [, end]]) -> int
Return the lowest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
>>>
Your example simply repeats:
index = string.find('banana', 'nana', 0) + 1 # index = 3
index = string.find('banana', 'nana', 3) + 1 # index = 0
The -1 version works because it correctly interprets the return value of string.find!
False is of type bool, which is a sub-type of int, and its value is 0.
In Python, False is similar to using 0, not -1
There's a difference between equality and converting to a boolean value for truth testing, for both historical and flexibility reasons:
>>> True == 1
True
>>> True == -1
False
>>> bool(-1)
True
>>> False == 0
True
>>> bool(0)
False
>>> True == 2
False
>>> bool(2)
True
I have always thought that using -1 in a condition is alway the same as the writing False (boolean value).
1) No. It is never the same, and I can't imagine why you would have ever thought this, let alone always thought it. Unless for some reason you had only ever used if with string.find or something.
2) You shouldn't be using the string module in the first place. Quoting directly from the documentation:
DESCRIPTION
Warning: most of the code you see here isn't normally used nowadays.
Beginning with Python 1.6, many of these functions are implemented as
methods on the standard string object. They used to be implemented by
a built-in module called strop, but strop is now obsolete itself.
So instead of string.find('foobar', 'foo'), we use the .find method of the str class itself (the class that 'foobar' and 'foo' belong to); and since we have objects of that class, we can make bound method calls, thus: 'foobar'.find('foo').
3) The .find method of strings returns a number that tells you where the substring was found, if it was found. If the substring wasn't found, it returns -1. It cannot return 0 in this case, because that would mean "was found at the beginning".
4) False will compare equal to 0. It is worth noting that Python actually implements its bool type as a subclass of int.
5) No matter what language you are using, you should not compare to boolean literals. x == False or equivalent is, quite simply, not the right thing to write. It gains you nothing in terms of clarity, and creates opportunities to make mistakes.
You would never, ever say "If it is true that it is raining, I will need an umbrella" in English, even though that is grammatically correct. There is no point; it is not more polite nor more clear than the obvious "If it is raining, I will need an umbrella".
If you want to use a value as a boolean, then use it as a boolean. If you want to use the result of a comparison (i.e. "is the value equal to -1 or not?"), then perform the comparison.