JamCoders

💾 Download

JamCoders Day 2 Lecture 1

Boaz Barak

Lists, strings, functions

Basic function syntax

In [ ]:
# This is function syntax
def FUNCTION_NAME(ARGUMENT1, ARGUMENT2):
    FUNCTION_BODY
    return RETURN_VALUE
In [ ]:
# indentation matters:
def FUNCTION_NAME(ARGUMENT1, ARGUMENT2):
FUNCTION_BODY
return RETURN_VALUE
  File "<ipython-input-4-80e17c86514b>", line 3
    FUNCTION_BODY
                ^
IndentationError: expected an indented block
In [ ]:
def thisIsAFunction(x):
    return x + 2
In [ ]:
# This is an example of calling a function
y = thisIsAFunction(100)
print(y)
print(x)
102
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-ba92ba9bafb1> in <module>()
      2 y = thisIsAFunction(100)
      3 print(y)
----> 4 print(x)

NameError: name 'x' is not defined
In [ ]:
# variables inside a function are internal to it
def function2(x):
    temp_var = x + 3
    return temp_var
In [ ]:
y = 100
z = function2(y)
print(f"y = {y}, z={z}")
y = 100, z=103
In [ ]:
temp_var
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-11-bcce3c898a8c> in <module>()
----> 1 temp_var

NameError: name 'temp_var' is not defined

move to powerpoint

In [ ]:
w = function2(z)
w
Out[ ]:
106
In [ ]:
# Function names DO NOT represent what the function does!
def multThree(x):
    return x * 2
In [ ]:
multThree(2)
Out[ ]:
4
In [ ]:
# You can call functions in functions
# You can also call functions on results of functions
def identityFunction(x):
    return x

def multByTwo(x):
    return 2 * x

def addOne(x):
    return x + 1

def mystery(x):
    return multByTwo(x) + addOne(identityFunction(x))

print(identityFunction(3))
print(multByTwo(3))
print(addOne(3))
3
6
4
In [ ]:
mystery(3) # what is the output?
Out[ ]:
10
In [ ]:
# Functions can have multiple argumentsI
def mystery2(a,b):
    if a-b>0:
        return True
    return False
In [ ]:
mystery2(10,9)
Out[ ]:
True
In [ ]:
# functions can take other types as well
def sum_of_last_elements(L):
    return L[-1] + L[-2]

sum_of_last_elements([1,3,5])
Out[ ]:
8
In [ ]:
F = [0,1]
i = 0
while i < 10:
    F.append(sum_of_last_elements(F))
    i += 1
print(F)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
In [ ]:
def starts_with_b(s):
    if s[0]=='b': 
        return True
    return False
starts_with_b("boaz")
Out[ ]:
True
In [ ]:
starts_with_b("Boaz")
Out[ ]:
False

Return is not the same as print

  • print(x) - prints x to the bottom of the cell. We can repeat it multiple times inside a function or also use it outside a function. Does not change the value that the function returns.

  • return x - returns the value x from the function. Can only use it inside a function and if it happens then it stops the execution of the function.

In [ ]:
def f(x):
    print(x)
    x = x*2
    print(x)
    
def g(x):
    return x
    x = x*2
    return x
In [ ]:
f(2)
2
4
In [ ]:
g(2)
Out[ ]:
2
In [ ]:
def f(x):
    return 2*x

def g(x):
    print(2*x)
In [ ]:
# Guess the output
f(2)
Out[ ]:
4
In [ ]:
# Guess the output
g(2)
4
In [ ]:
# Guess the output
f(f(2))
Out[ ]:
8
In [ ]:
# Guess the output
g(g(2))
4
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-31-b8ccaa3b9445> in <module>()
      1 # Guess the output
----> 2 g(g(2))

<ipython-input-26-0dca424b05f0> in g(x)
      3 
      4 def g(x):
----> 5     print(2*x)

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

Questions?

`# This is formatted as code`

Lists (skip)

In [ ]:
# Lists are indexed STARTING FROM 0
# You can retreive elements from a list using LIST[INDEX] notation
x = [0, 1, 2, 3, 4, 5]
print(x[0])
print(x[1])
In [ ]:
x = ['hello', 'world', 'how', 'do', 'you', 'do']
print(x[2])
In [ ]:
# Indexing from negative numbers gives elements from the back
x = ['hello', 'world', 'how', 'do', 'you', 'do']
print(x[0])
print(x[1])
print(x[-1])
print(x[-2])
print(x[2])
print(x[-4])
In [ ]:
# len(LIST) gives you the length of the list
x = ['hello', 'world', 'how', 'do', 'you', 'do']
len(x)
In [ ]:
# Which can be helpful with long lists
x = [32, 43, 45, 532, 3, 4, 14, 32, 1, 31, 3, 13, 3, 51, 1, 1]
len(x)

List slicing

If L is a list $[X_0,X_1,X_2,.....,X_{n-1}]$ then L[$i$:$j$] gives all the elements from index $i$ to index $j-1$. (Elements $X_i,X_{i+1},...,X_{j-1}$)

In [ ]:
# List slicing can give you parts of lists
x = [32, 43, 45, 532, 3, 4, 14, 32, 1, 31, 3, 13, 3, 51, 1, 1]
print(x[0:1])
print(x[0:2]) 
print(x[0:5]) #x[0], x[1], x[2], x[3], x[4]
In [ ]:
# It does not include the last element past the colon
x = [32, 43, 45, 532, 3, 4, 14, 32, 1, 31, 3, 13, 3, 51, 1, 1]
x[1:5]
In [ ]:
# If you don't have something past the colon, it takes until the end
x = [32, 43, 45, 532, 3, 4, 14, 32, 1, 31, 3, 13, 3, 51, 1, 1]
x[5:]
In [ ]:
# If you don't have something before the colon, it takes from the start
x = [32, 43, 45, 532, 3, 4, 14, 32, 1, 31, 3, 13, 3, 51, 1, 1]
x[:5]
In [ ]:
# The above syntax works with negative indexes
x = [32, 43, 45, 532, 3, 4, 14, 32, 1, 31, 3, 13, 3, 51, 1, 1]
x[-3:]
In [ ]:
x = [32, 43, 45, 532, 3, 4, 14, 32, 1, 31, 3, 13, 3, 51, 1, 1]
x[:-4]

Modifying lists

You can change a list L in several ways:

  • L[5] = 7 - changes the 6th element of L to be 7

  • L.append(17) - adds the number 17 at the end of the list

  • L.insert(2,17) - adds the number 17 just before the third element of the list

In [ ]:
x = [0, 1, 2, 3, 5]
print(x)
x[4] = 10
print(x)
x[2]=-1
print(x)
In [ ]:
L = [0,1,2,3,4]
L.append(5)
L.insert(0,-1)
print(L)
In [ ]:
# Lists can have mixed types
x = [1, 2, 'hi', 4.0, True, None]
x

String indexing (skip)

In [ ]:
# String indexing follows the same rules as list indexing
x = 'Hello world!'
x[0]
In [ ]:
x = 'Hello world!'
x[7]
In [ ]:
# You can also use len with strings
x = 'Hello world!'
len(x)

Strings are immutable

In [ ]:
x = 'Hello world!'
x[0] = 'B'
In [ ]:
# But we can do the following
x = 'B' + x[1:]
x

Didn't we just change the string x?

Extra: Lists of lists

In [ ]:
L = [[1,2,3],[4,5,6],[7,8,9]]
# what will be printed?
L[1]
In [ ]:
# what will be printed?
L[1][2]
In [ ]: