by Eugeniy E. Mikhailov and Greg Bentsen
Variable of boolean type can have only two values
False (case is
important) and recognizes 0 as a
substitute)True, also
1 to
indicate true, but actually everything except zero can be used!)There are three logical operators which are used in boolean algebra
not
and
or
Assume
what is the resulting value of
not
has highest precedence, then and, and then
or
“Cat is an animal and cat is not an animal”
is a false statement
“To be or not to be”
The answer is always True
There is an island, which is populated by two kind of people: liars and truthlovers.
Suppose you land on this island and meet a person. What will be the answer to your question “Who are you?”
Now you see a person who answers to your question. “I am a liar.”
Is it possible?
>>> True and 13
13
>>> True or 13
True
>>> 123.3 and 12
123.3
>>> 123.3 or 14
123.3
>>> True + True
2
>>> False + True
1Do not make you program depending on strange mix of logic and numbers math.
It is very hard to wrap your mind around such use.
| Math or human notation | Python |
|---|---|
== double equal sign! |
|
!= |
|
< |
|
<= |
|
> |
|
>= |
numpy arrays)It is done element-wise, i.e. we apply comparison to every element independently
We get back a 2D array
Unconventional but technically correct
The value of ‘D’ is always 4, except the case when y=0
assignment operator (=) is not equality operator (==)
We can skip else when we do
not need it
while
loop is extremely useful but they are not guaranteed to finish.
For a bit more complicated conditional statement and the loop body, it is hard to predict if the loop will finish.
In this case variable is assigned consequently with values taken from
list_like and then statements
inside of the loop are executed
for
loops are guaranteed to complete after predictable number of iterations
(the amount of columns in expression).
Calculate sum As long as , where .
Using while loop
Calculate sum As long as , where .
When dealing with numerical operations, often it is more elegant to use Python array operators. It is also much faster if the body of the loop is executed many times (> 1000).
>>> import numpy as np
... k = np.arange(5,101) # again notice +1 to the upper end
... k = 1.0*k # this looks useless, but it converts integer to float needed for `np.pow`
... a_k = np.pow(k, -k)
... S = np.sum( a_k[a_k >= 10**(-5)] )
... print(S)
...
0.0003414334705075446Note
np.sum
functionnumpy module