Programming · Input & Output
up to +100 XP
Stop 2.5 · Programming · 3 min

Input & Output

Learn to interact with users and display information

Learning objectives:
  • Implement keyboard input, screen output and text files (2.5.1)
  • Open, read, write lines to and close text files (2.5.2)
  • Interpret, create and debug input/output code (2.5.3–2.5.5)

Keyboard input and screen output

input() shows a prompt and returns what the user types as a string. print() displays output on the screen.

name = input("Enter your name: ")
age = int(input("Enter your age: "))
print("Hello", name)
print("Next year you will be " + str(age + 1))

Text files

A text file stores data so it is kept after the program ends.

Writing to a file

file = open("scores.txt", "w")    # "w" opens for writing (replaces the file)
file.write("Ali,72\n")
file.write("Bea,85\n")
file.close()                       # always close the file

Reading from a file

file = open("scores.txt", "r")    # "r" opens for reading
for line in file.readlines():
    name, score = line.strip().split(",")
    print(name, int(score))
file.close()

Useful commands from Appendix 2: open(), write(), read(), readline(), readlines(), close(), line.strip() (removes the newline) and line.split() (breaks a line into parts).

Why close the file? Closing saves any data still waiting to be written and frees the file for other programs.

Common input/output bugs

Quick check · 11 questions · up to 100 XP

Check what stuck.

+10 XP each
Question 1

Question 1 of 11

Which function gets keyboard input from the user?

Question 2

Question 2 of 11

Which mode opens a text file for writing?

Question 3

Question 3 of 11

What happens if you open an existing file with "w"?

Question 4

Question 4 of 11

Why should you close a file after using it?

Question 5

Question 5 of 11

What does line.strip() do?

Question 6

Question 6 of 11

Which command reads every line of a file into a list?

Question 7

Question 7 of 11

What error is caused by "5" + 1?

Question 8

Question 8 of 11

What does "Ali,72".split(",") return?

Question 9

Question 9 of 11

Opening a file that does not exist in "r" mode causes…

Question 10

Question 10 of 11 · Fill in the blanks

In Python, reads what the user types and displays output on the screen.

Question 11

Question 11 of 11 · Coding

Write greet(name) that returns "Hello, " followed by the name and "!". For example greet("Ada") returns "Hello, Ada!".

Open the IDE
Hint

Join strings with + : "Hello, " + name + "!"