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
- Doing maths on
input()without converting it:"5" + 1causes aTypeError. - Opening a file with
"w"when you meant to read it: this wipes the file. - Opening a file that does not exist with
"r"gives aFileNotFoundError. - Forgetting
\nwhen writing lines, so everything ends up on one line. - Forgetting
strip(), so values keep a hidden newline character.