01
What does this program print?
def process(n):
result = 0
while n > 0:
result = result + n % 10
n = n // 10
return result
print(process(234))
Output
Read each program carefully. Trace through it line by line on paper. Then write what you believe the program will print in the box provided.
Three short programs without recursion. Get into the rhythm of tracing before things get interesting.
def process(n):
result = 0
while n > 0:
result = result + n % 10
n = n // 10
return result
print(process(234))
def check(a, b):
if a > b:
return a - b
else:
return b - a + 1
print(check(5, 3))
print(check(2, 7))
def square(x):
return x * x
def compute(a, b):
return square(a) + square(b)
print(compute(3, 4))
A function that calls itself. Pay close attention to when work happens — before the recursive call, or after it.
def fun(n):
if n == 0:
return
print(n, end=" ")
fun(n - 1)
fun(4)
def fun(n):
if n == 0:
return
fun(n - 1)
print(n, end=" ")
fun(4)
def total(n):
if n == 0:
return 0
return n + total(n - 1)
print(total(5))
def fact(n):
if n == 1:
return 1
return n * fact(n - 1)
print(fact(5))
def fun(n):
if n == 0:
return
print(n, end=" ")
fun(n - 1)
print(n, end=" ")
fun(3)
def power(a, b):
if b == 0:
return 1
return a * power(a, b - 1)
print(power(2, 4))
def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
print(fib(5))