Let’s get started with the lesson! You are probably expecting this – here’s a quiz to check whether you remember everything that we have covered so far!
1
2
3
4
5
6
7
8
9
❮
❯
What is the output after executing the following piece of code? Type Error
if you are expecting an error or an infinite recursion.
def triangle_num ( n ):
return n + triangle_num ( n - 1 )
print ( triangle_num ( 3 ))
Explanation:
This function results in an infinite recursion. Remember that recursive functions should always define at least one base case , in addition to recursive/inductive case(s).
Check answer!
What is the output after executing the following piece of code? Type Error
if you are expecting an error or an infinite recursion.
def triangle_num ( n ):
if n < 1 :
return None
elif n == 1 :
return 1
else :
return n + triangle_num ( n - 1 )
print ( triangle_num ( 3 ))
Explanation:
This function computes the triangle number in a triangle number sequence recursively. It adds up the numbers from 1
to n
.
Check answer!
What is the output after executing the following piece of code?
try :
index = "python" . index ( "s" )
except ValueError :
print ( "no" )
else :
print ( "yes" )
finally :
print ( "done" )
Explanation:
Line 2 will cause a ValueError
to be raised (because "s"
cannot be found in the string "python"
). The error will be caught by the except
clause in Lines 3-4. Finally, the finally
clause in Lines 7-8 will be executed, since this will run whether or not an error occurs.
Check answer!