Talking with Your Program · practice
Turn Text into a Whole Number
The previous lesson introduced a pattern you can now reuse:
function(argument) -> return value
int() is another
book_count = int(book_count_text)
In this call:
intis the function.book_count_textis the argument.The converted integer is the
. The
stores that return value in book_count.
The arrow above is explanatory notation, not Python syntax.
Turn typed text into a whole number
When an answer represents a whole number, use int() to convert the
book_count_text = input("How many books? ")
book_count = int(book_count_text)
The first line collects text. The second line calls int() with that text and stores the returned integer.
If the person enters 12, the values are:
| Value | Type | |
|---|---|---|
book_count_text | "12" | str |
book_count | 12 | int |
The quotation marks in the table help show the difference. They are not part of what the person typed.
Conversion produces a new value
int(book_count_text) does not change the original string. It produces a new integer value, which this program assigns to book_count.
Now arithmetic works:
after_one_more = book_count + 1
If book_count is 12, after_one_more becomes 13.
Here is the complete book-count example:
book_count_text = input("How many books? ")
book_count = int(book_count_text)
after_one_more = book_count + 1
print(f"With one more, you would have {after_one_more} books.")
Notice the three distinct values: the original string, the converted integer, and the result of the calculation.
A shorter form
You may also see the function calls nested:
book_count = int(input("How many books? "))
Python works from the inside out. input() returns a string, then int() receives that string as its argument and returns an integer.
Both forms work. Separate lines are often easier to inspect while you are learning or debugging.
The variable number_text contains the string "7". What will this program print?
number_text = "7"
number = int(number_text)
print(number + 2)Finish the age program
The starter program collects an age as text. Two placeholder values still prevent it from calculating the following year’s age.
Replace those placeholders so the program:
converts the value in
age_textto an integer namedage;calculates
next_ageby adding1toage.
Keep the final 40, the final line should be:
Next year you will be 41.
Do not copy the book variable names into the exercise. Apply the same function pattern to the age variables already present in the starter code.
During Run, use a whole number. During Submit, Python Land supplies its own whole-number answer.
Task
Convert age_text with int() to an integer named age, then calculate next_age by adding 1 to age. Keep the final next_age.
If the input is 40, the final line should be:
Next year you will be 41.