← Back to course
Code Crew G4 / Week 09 / Tuesday
2/6
Week 09 Β· Input, process, output

Tuesday

Text or number?
// Programs that ask questions
⏱ about 15 min

Tuesday: Text or number?

Rocket writes a program that asks how many crates arrived, then doubles it for the order form. The user types 4. The screen proudly shows 44.

"Forty-four?" Rocket says. "Four plus four is eight!" Raven laughs kindly. "What do you notice? Where have we seen 3 and 4 make 34 before?"

Rocket remembers week one. "Strings!" Nova glows. "Great discovery! Would you like a hint? Python has a command that turns digits into a real number."

input always gives a string

input always gives back a string, even when the user types digits.

Plus joins strings, so "4" + "4" makes "44".

int turns a string of digits into a number. Then plus adds.

crates = input("Crates in? ")
print(crates + crates)
The screen showsThe user types
Crates in?4
44
crates = int(input("Crates in? "))
print(crates + crates)
The screen showsThe user types
Crates in?4
8

int(input("Crates in? ")) does two jobs. input gets the string "4". Then int turns it into the number 4.

In the first program, the user types 7. What shows?
In the second program, the user types 7. What shows?
ExpressionIs the result a number?
int("12")?
input("Age of the ship? ")?
"5" + "5"?
int("3") + 2?
WHY THIS EXERCISEKnowing which values are strings and which are numbers stops surprises.
WHY THE ERROR?
  • Read the question.
  • Tap your answer.
A user types four, spelled out in letters. What happens at int(answer)?
Try it
Write two strings and two numbers on paper.
For each pair, write what plus would make.

Practice lab: join or add?

a = input("First? ")
b = input("Second? ")
print(a + b)
print(int(a) + int(b))
The screen showsThe user types
First?3
Second?9
39
12
The user types 10, then 5. What does line 3 show?
What does line 4 show for that run?
The user types 2, then 2. What does line 3 show?
STRING OR NUMBER?
  • Read the question.
  • Tap your answer.
What kind of value does input give back?
What does int("20") give?
What does int("7") * 2 give?
StatementTrue or false?
"6" + "1" makes "61".?
int("6") + 1 makes 7.?
int("six") makes 6.?
input turns digits into numbers by itself.?
WHY THIS EXERCISEinput gives strings, and int only understands digits.
n = int(input("Fuel? ")) runs, and the user types 25. What does print(n + 5) show?
WHY THIS EXERCISEint made the answer a number, so + adds.

Sharp thinking! Tomorrow you will use numbers from the user to work things out.

← Monday