Gulberg Green, Islamabad

Programming Fundamentals · Lesson 03

Input and output

Ask a question, collect an answer, and display a result.

Programs can work with information supplied while they run. In Python, input displays a prompt and waits for the user to type a line and press Enter. It returns that line as a string.

If you want to do arithmetic with a number someone types, convert the text first. The int function converts text such as "4" into the integer 4. Try the example with the whole number 4.

Input makes a program interactive. This first version expects a whole number. Entering a word or a decimal such as 4.5 will raise a ValueError because int cannot interpret that string as a whole number.

Read the example

Python 3
people = int(input("How many people? "))
cups = people * 2
print("Cups needed:", cups)
Expected output
How many people? 4
Cups needed: 8

The 4 in the sample is typed by the user. Python converts it to an integer, multiplies it by two, then prints the label and the result separated by a space.

Try it yourself

A workshop needs three pencils per person. Ask how many people are coming and display the pencil count. Check your result for five people.

Show a worked solution
people = int(input("How many people? "))
print("Pencils needed:", people * 3)  # 15 for five people

Check your understanding

Your lesson quiz

Answer all five questions. Score at least 4 out of 5 (80%) to pass. You can retry as often as you like.

1. What type does input return?
2. What does int("4") produce?
3. For 5 people and 3 pencils each, how many pencils are needed?
4. What happens with int("4.5")?
5. Which line displays a calculated cups value with a label?

Quiz progress is saved in this browser. View certificates →

Learn together

Was this lesson helpful?

Comments and reactions are not open yet.

WhatsApp