Start with role-playing function call.
A function is a named sequence of statements that performs a computation.
def function_name(arguments): # Header
statement(s) # Body
return result
type(len)
builtin_function_or_method
range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
len(range(0, 10))
10
type(range)
builtin_function_or_method
help(range)
Help on built-in function range in module __builtin__: range(...) range(stop) -> list of integers range(start, stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements.
def double(n): # double is the function name, n is the argument or parameter to the function
''' Returns 2 * n ''' # This is a docstring which annotates the function
return n + n
double(1) # Call function to execute body with argument of 1
2
double(double(1)) # Use result of function as argument to another function
4
result = double(1) # Store result of function in a variable by using assignment
A fruitful function returns a value to the caller via the return
statement. In contrast, a void function returns nothing (ie. None
) and may omit a return
statement.
def quadruple(n):
return double(double(n)) # Fruitful
quadruple(3)
12
result = quadruple(3)
result
12
def quadruple(n):
print double(double(n)) # Void
quadruple(3)
12
result = quadruple(3)
12
result
Inside a function, the arguments are assigned to local variables called parameters. These local variables are isolated/different from variables outside the function (even if they share the same name).
x = 1 # Global variable
def print_number(x): # Local variable
print x
print x
print_number(2)
1 2
x = 1 # Global variable
def increment(x): # Local variable
x = x + 1 # This x is different from global x
return x
print increment(x)
print x
2 1
A function, is_even, that determines whether not a number n is even.
A function, average, that determines the average value of a list.
def is_even(n):
''' Returns whether or not n is even '''
return n % 2 == 0
is_even(1)
False
is_even(4)
True
def average(lst):
''' Returns average of list '''
return float(sum(lst)) / len(lst)
average([1, 2, 3, 4])
2.5
import random
from ipywidgets import interact
MIN = 1
MAX = 10
TARGET = random.randint(MIN, MAX)
def guessing_game(guess):
if guess < TARGET:
print 'Higher!'
elif guess > TARGET:
print 'Lower!'
else:
print 'Hooray, you found it!'
interact(guessing_game, guess=(MIN, MAX))
<function __main__.guessing_game>
A list is a sequence of values. Individual values in a list are called elements or items.
Lists have a type and are considered values themselves.
Lists may contain elements of different types (though this is unusal).
[0, 1, 2, 3] # Create a list containing 4 numbers
[0, 1, 2, 3]
numbers = [0, 1, 2, 3] # Create a list containing 4 numbers and assign it to variable
numbers
[0, 1, 2, 3]
type(numbers)
list
len(numbers) # Get number of items in list
4
numbers[0] # Access first element
0
numbers[1] # Access second element
1
numbers[-1] # Access last element
3
numbers[0] = 'zero' # Modify first element
numbers
['zero', 1, 2, 3]
numbers[1 + 2] # We can use any integer to access elements
3
numbers[5] # Out of bounds access leads to an error
IndexErrorTraceback (most recent call last) <ipython-input-59-da3c04d54a36> in <module>() ----> 1 numbers[5] # Out of bounds access leads to an error IndexError: list index out of range
for number in numbers: # Iterate over every element in list
print number
zero 1 2 3
for index in range(len(numbers)): # Iterate over every index in list
print index
0 1 2 3
for index, number in enumerate(numbers): # Iterate over every index and element in the list
print index, number
0 zero 1 1 2 2 3 3
[] # Create an empty list
[]
list() # Another way to create any empty list
[]
if numbers: # A non-empty list evaluates to True in a boolean expression
print 'List is not empty!'
List is not empty!
if not []: # An empty list evaluates to False in a boolean expression
print 'List is empty!'
List is empty!
Write code that performs the following:
Print the first and last element of in the list.
Print all the elements of a list except for the first and list.
Print the smallest and largest items in a list.
Print out a list in sorted order.
Print out every other item in the list.
# Print the first and last element of in the list.
numbers = [5, 4, 7, 0, 1]
print numbers[0], numbers[-1]
5 1
# Print all the elements of a list except for the first and list.
print numbers[1:-1]
[4, 7, 0]
# Print the smallest and largest items in a list.
print min(numbers), max(numbers)
0 7
# Print out a list in sorted order.
print sorted(numbers)
[0, 1, 4, 5, 7]
# Print out every other item in the list.
for index, number in enumerate(numbers):
if index % 2 == 0:
print number
for index in range(0, len(numbers), 2):
print numbers[index]
5 7 1 5 7 1
Write a function called search, which returns the index of the item (needle) if it is in the list (haystack). If the item is not in the list, then -1 should be returned.
def search(haystack, needle):
''' Returns index of needle in haystack list '''
…
def search(haystack, needle):
''' Returns index of needle in haystack list '''
for index, item in enumerate(haystack):
if item == needle:
return index
return -1
search([5, 4, 0, 7, 1], 1)
4
search([5, 4, 0, 7, 1], 9)
-1
def search(haystack, needle):
''' Returns index of needle in haystack list '''
index = 0
found = -1
while index < len(haystack) and found < 0:
if haystack[index] == needle:
found = index
index += 1
return found
search([5, 4, 0, 7, 1], 1)
4
search([5, 4, 0, 7, 1], 9)
-1
def bubblesort(lst):
swapped = True
while swapped:
swapped = False
for i in range(0, len(lst) - 1):
if lst[i] > lst[i + 1]:
lst[i], lst[i + 1] = lst[i + 1], lst[i]
swapped = True
return lst
data = range(10000)
random.shuffle(data)
%timeit bubblesort(data)
The slowest run took 14914.75 times longer than the fastest. This could mean that an intermediate result is being cached. 1 loop, best of 3: 476 µs per loop
%timeit sorted(data)
The slowest run took 4.58 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 146 µs per loop
Write code that simulates a Magic 8-Ball by prompting the user for a question and then randomly printing one of the following outcomes:
OUTCOMES = [
'It is certain',
'It is decidedly so',
'Without a doubt',
'Yes definitely',
'You may rely on it',
'As I see it, yes',
'Most likely',
'Outlook good',
'Yes',
'Signs point to yes',
'Reply hazy try again',
'Ask again later',
'Better not tell you now',
'Cannot predict now',
'Concentrate and ask again',
"Don't count on it",
'My reply is no',
'My sources say no',
'Outlook not so good',
'Very doubtful',
]
question = raw_input("What is your question? ")
#outcome = OUTCOMES[random.randrange(len(OUTCOMES))]
outcome = OUTCOMES[random.randint(0, len(OUTCOMES) - 1)]
#outcome = random.choice(OUTCOMES)
print outcome
What is your question? asdf It is certain