Final challenge: split a program into named parts
After this: Predict, complete and explain programs built from functions.
This challenge has five steps, and each step is scored on its own. You will predict what a program made of functions prints, write a function's first line, say which frames are open at a moment in a run, tell print from return, and say where a variable lives. Every step shows the code in Python and in Java; the answers are the same in both, except where the lesson said that Java refuses a line. You can try as many times as you like, and hints work as they do in the lessons.
Step 1 of 5Predict it
Predict it
One function, called twice on the same line. What does this print?
def price(count, each): return count * each
print(price(3, 4) + price(1, 2))public class Main { static int price(int count, int each) { return count * each; }
public static void main(String[] args) { System.out.println(price(3, 4) + price(1, 2)); }}Write the first line
Complete the first line of area, with the two parameters w and h, so that the program prints 12. End it with a colon.Give each parameter its type, and say what type the function returns.
____________________ # ← the first line: area, with inputs w and h return w * h
print(area(3, 4))public class Main { ____________________ // ← the first line: area, with inputs w and h return w * h; }
public static void main(String[] args) { System.out.println(area(3, 4)); }}Count the frames
The program calls a(5), and a calls b. At the moment b is running, which function frames are open, besides the program's? And what is printed at the end?
def a(x): return b(x) + 1
def b(x): return x * 2
print(a(5))Output
11
public class Main { static int a(int x) { return b(x) + 1; }
static int b(int x) { return x * 2; }
public static void main(String[] args) { System.out.println(a(5)); }}Output
11
print or return
tally has two parameters and one line, which prints their sum. It has no return line. A program writes result = tally(2, 3)int result = tally(2, 3); and then prints result. What happens?
Where it lives
A box named n outside, and a line n = 50int n = 50; inside. What does this print?
n = 1
def work(): n = 50 return n + 1
print(work())print(n)public class Main { static int n = 1;
static int work() { int n = 50; return n + 1; }
public static void main(String[] args) { System.out.println(work()); System.out.println(n); }}- Predict what a program of functions prints, write a function's first line, say which frames are open, tell print from return, and say where a variable lives.