for
loopsteaching.rouxl.es
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
fib(n - 1)
and fib(n - 2)
)+
)+
, -
, *
, /
or some other function (max
, min
, etc).You can also write down
def fib(n):
if n == 0 or n == 1:
return n
else:
return fib(n - 1) + fib(n - 2)
[1, "hello", [2, "hi"]]
In general, to create a list, you wrap something in square brackets
[1, 2, 3]
creates a list.Syntax is lst[<start index>:<end index>:<step>]
; this creates a copy of all or part of your list (will be important later)
start index
is inclusive (if not included, it defaults to the first value)end index
is exclusive (if not included, it defaults to the end of the list)step
can be negative!lst = [3, 4, 5]
lst[:] # Makes a copy; returns [3, 4, 5]
lst[1:] # [4, 5]
lst[::-1] # [5, 4, 3]
lst[::2] # [3, 5]
for <variable> in <sequence>:
[body of for loop]
Example:
lst = [3, 4, 5]
for elem in lst:
print(elem)
Very similar to for
loops, but can be done in 1 line!
[<expression> for <variable> in <sequence> [if <condition>]]
lst = [3, 2, 1]
[x * 2 for x in lst if x < 3] # [4, 2]
[x * 2 for x in [3, 2, 1]] # [6, 4, 2]
links.rouxl.es/disc
)keys
to values
keys
must be 'hashable'
values
can be anything (including other dictionaries)keys
rather than indiceskeys
to values
keys
rather than indices{}
)
{key: value}
Demo:
pokemon = {'pikachu': 25, 'dragonair': 148, 25: 'hello'}
pokemon['pikachu'] # 25
pokemon['hello'] = 'hi'
pokemon # {'pikachu': 25, 'dragonair': 148, 25: 'hello', 'hello': 'hi'}
links.rouxl.es/feedback
Thanks for coming!
Please give me feedback on what to improve!