Print and None
>>> 'Go Bears'
'Go Bears'
>>> print('Go Bears')
Go Bears
>>> None
>>> print(None)
None
None
is special in Python, it represents nothing.
A function that does not explicitly return a value will return None
.
Note: None
is not displayed by the interpreter as the value of an expression
>>> x = -2
>>> x
-2
>>> x = print(-2)
-2
>>> x
>>> print(x)
None
An interesting example:
>>> print(print(1), print(2))
1
1
None None
Pure Functions & Non-Pure Functions
- Pure functions just return values
- Non-pure functions have side effects
print
is an example of a non-pure function, because it has side effects. A side effect isn’t value, but anything that happens as a consequence of calling a function.
Multiple Environments
With a def statement:
- A new function is created
- Name is bound to that funciton in the current frame
With a Call expression:
- The operator & operand(s) are evaluated
- The function (value of operator) is called on the arguments (value of operands)
Note: A name evaluates to the value bound to that name in the earlist frame of the current environment in which that name is found.
Miscellaneous Python Features
Operator | What it does |
---|---|
/ |
True Division |
// |
Floor Division |
Something interesting:
>>> from operator import *
>>> mod(3, 2)
1
>>> mod(3.0, 2)
1.0
>>> mod(3.1, 2)
1.1
>>> mod(3.2, 2)
1.2000000000000002
Statements
A statement is executed by the interpreter to perform an action.
A compound statement consists of one or more clauses, each of which has a header and a suite. def
is a compound statement.
- The first header of the compound statement determines the statement type
- The subsequent header of each clause controls the suite that follows
Boolean Contexts
Falsey values in Python:
False, 0, '', None, [] # There are more!!
Iteration
>>> i, total = 0, 0
>>> while i < 3:
... i += 1
... total += i
...
>>> i
3
>>> total
6
Execution Rule for while
Statements
- Evaluate the header’s expression
- If it is truthy, execute the suite, then return to step 1.
Short-Circuting
and
returns the first falsey value, if any.or
returns the first truthy value, if any.- If
and
andor
do not short-circuit, they return the last value.
Things to Take Note
Here’s something for you to ponder:
>>> 0 == False
True
>>> 1 == True
True
>>> 2 == True
False
>>> 2 == False
False
More to ponder: Why does the boolean value get casted to an integer first, and not the integer casted to a boolean first?
Python Operator Precedence
Common ones in descending precedence (most binding to least binding):
Operators |
---|
** |
*, @, /, //, % |
+, - |
in, not in, is, is not, <, <=, >, >=, !=, == |
if – else |
not |
and |
or |
lambda |
Here is the official Python Operator Precedence Chart in case you’re interested.
Hey, kudos for making it this far! If you've liked this, you might also like Names.