Logic & Arithmetic
Mastering logic, looping, and defining functions in Python.
Control Flow
As in most programming languages, you can perform an action conditionally using if:
if 1 > 2:
message = "if only 1 were greater than two..."
elif 1 > 3:
message = "elif stands for 'else if'"
else:
message = "when all else fails use else (if you want to)"You can also write a ternary if-then-else on one line, which we will do occasionally:
parity = "even" if x % 2 == 0 else "odd"Python has a while loop:
x = 0
while x < 10:
print x, "is less than 10"
x += 1although more often we’ll use for and in:
for x in range(10):
print x, "is less than 10"If you need more-complex logic, you can use continue and break:
for x in range(10):
if x == 3:
continue # go immediately to the next iteration
if x == 5:
break # quit the loop entirely
print xThis will print 0, 1, 2, and 4.
Truthiness
Booleans in Python work as in most other languages, except that they’re capitalized:
one_is_less_than_two = 1 < 2 # equals True
true_equals_false = True == False # equals FalsePython uses the value None to indicate a nonexistent value. It is similar to other languages’ null:
x = None
print x == None # prints True, but is not Pythonic
print x is None # prints True, and is PythonicPython lets you use any value where it expects a Boolean. The following are all "Falsy":
FalseNone[](an empty list){}(an empty dict)""set()00.0
Pretty much anything else gets treated as True. This allows you to easily use if statements to test for empty lists or empty strings or empty dictionaries or so on. It also sometimes causes tricky bugs if you’re not expecting this behavior:
s = some_function_that_returns_a_string()
if s:
first_char = s[0]
else:
first_char = ""A simpler way of doing the same is:
first_char = s and s[0]since and returns its second value when the first is "truthy," the first value when it’s not. Similarly, if x is either a number or possibly None:
safe_x = x or 0is definitely a number.
Python has an all function, which takes a list and returns True precisely when every element is truthy, and an any function, which returns True when at least one element is truthy:
all([True, 1, { 3 }]) # True
all([True, 1, {}]) # False, {} is falsy
any([True, 1, {}]) # True, True is truthy
all([]) # True, no falsy elements in the list
any([]) # False, no truthy elements in the listArithmetic
Python 2.7 uses integer division by default, so that 5 / 2 equals 2. Almost always this is not what we want, so we will always start our files with:
from __future__ import divisionafter which 5 / 2 equals 2.5. Every code example in this book uses this new-style division. In the handful of cases where we need integer division, we can get it with a double slash: 5 // 2.
Functions
A function is a rule for taking zero or more inputs and returning a corresponding output. In Python, we typically define functions using def:
def double(x):
"""this is where you put an optional docstring
that explains what the function does.
for example, this function multiplies its input by 2"""
return x * 2Python functions are first-class, which means that we can assign them to variables and pass them into functions just like any other arguments:
def apply_to_one(f):
"""calls the function f with 1 as its argument"""
return f(1)
my_double = double
x = apply_to_one(my_double) # equals 2It is also easy to create short anonymous functions, or lambdas:
y = apply_to_one(lambda x: x + 4) # equals 5You can assign lambdas to variables, although most people will tell you that you should just use def instead:
another_double = lambda x: 2 * x # don't do this
def another_double(x): return 2 * x # do this insteadFunction parameters can also be given default arguments, which only need to be specified when you want a value other than the default:
def my_print(message="my default message"):
print message
my_print("hello") # prints 'hello'
my_print() # prints 'my default message'It is sometimes useful to specify arguments by name:
def subtract(a=0, b=0):
return a - b
subtract(10, 5) # returns 5
subtract(0, 5) # returns -5
subtract(b=5) # returns -5We will be creating many, many functions.
Strings
Strings can be delimited by single or double quotation marks (but the quotes have to match):
single_quoted_string = 'data science'
double_quoted_string = "data science"Python uses backslashes to encode special characters. For example:
tab_string = "\t"
len(tab_string) # is 1If you want backslashes as backslashes (which you might in Windows directory names or in regular expressions), you can create raw strings using r"":
not_tab_string = r"\t"
len(not_tab_string) # is 2You can create multiline strings using triple-[double-]-quotes:
multi_line_string = """This is the first line.
and this is the second line
and this is the third line"""Exceptions
When something goes wrong, Python raises an exception. Unhandled, these will cause your program to crash. You can handle them using try and except:
try:
print 0 / 0
except ZeroDivisionError:
print "cannot divide by zero"Although in many languages exceptions are considered bad, in Python there is no shame in using them to make your code cleaner, and we will occasionally do so.