Python Input and int(): Convert Text to Numbers
Read text and convert it
input() reads one line of user input and returns a string (text). A prompt inside its parentheses tells the user what to enter. If the user types 7, the returned value is the string "7", not the integer 7. int() converts valid whole-number text into an integer that can be used in arithmetic.
text = input("Number: ")number = int(text)print(number + 3)In a real terminal, the user types 7 and presses Enter; the program displays 10. A terminal may echo the typed input. This sample requires standard input; an online editor may not support interactive prompts. For predictable practice use the fixed-text example below.
Simulate input without waiting for a user
text = "12"print(text + "3")number = int(text)print(number + 3)With strings, + joins the text, producing 123. After conversion, + adds numbers, producing 15. When converting whole-number text, leading/trailing spaces and a leading plus or minus sign can be accepted by int(). For now, enter ordinary base-ten whole numbers.
Recognize invalid number text
seven is not valid integer text, so the conversion raises ValueError. A decimal string such as "2.5" is not valid input for int() either. Do not ignore the error or silently guess the intended number. Error handling and other numeric types are covered later.
Apply conversion to a ticket count
Set text = "8", convert it to an integer, and display the number of tickets after adding two. For the challenge the grader supplies a string directly to the provided function; do not call input() or print in the function. Return the computed integer.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Input and integer conversion
Check your understanding of input and conversion.
A user types 12 at an input() prompt. What does input() return?
What is printed?
print("5" + "3")What is printed?
print(int("5") + 3)What happens when Python evaluates int("2.5")?
int("2.5")What is printed?
print(int(" +5 ") + 7)