A program that talks to you
A game asks for your name. You type it. The game says: Hello, Sam!
Two things happened. The program received data from you. Then it showed data to you. Every program that talks to people does these two jobs.
Key words
| Word | What it means | Example |
|---|---|---|
| Input | Data that goes into a program. | what you type |
| Output | Data that a program shows or gives out. | text on the screen |
| Keyboard | The device you type on. It gives input. | typing a name |
| Screen | The device that shows output. | text from print() |
| Prompt | A message that tells the user what to type. | "Age? " |
| String | Text inside quote marks. | "Sam" |
| Integer | A whole number. | 15 |
| Float | A number with a decimal point. | 2.5 |
| Variable | A name that holds a value. | name |
| Exception | An error that stops a program while it runs. | ValueError |
The cells students fill in are left blank in this preview.
Try it: print to the screen
print("Hello")
print("Total:", 7)
print("Score: " + str(10))
team = "Leeds"
goals = 3
print("{} scored {} goals".format(team, goals))
# print() shows output on the screen.
# Change the team and goals and run again.
print() is output
print() shows something on the screen. You can print text, numbers and variables.
To join text and a number, change the number with str() and use +. Or use format(). It puts values into the {} gaps in the text, in order.
input() asks the user
name = input("What is your name? ")
print("Hello, " + name)
age = int(input("Age? "))
print("Next year you will be", age + 1)
# Run this on your own computer or in the practice editor.
# input() waits for the user to type and press Enter.
input() always gives a string
data-callouts.warning.label
Whatever the user types, input() gives it back as text. The number 15 arrives as "15". To calculate with it, change it with int() or float().
What does it show?
Have a go
What does it show?
3 questionsYour answers are marked here and are not kept. A college account keeps every student’s marks.
Worked example: follow the program
| Step | What happens | age holds | On screen |
|---|---|---|---|
| 1 | Python shows the prompt Age? | nothing yet | Age? |
| 2 | The user types 15 and presses Enter | "15" (a string) | |
| 3 | int() changes the text to a number | 15 (an integer) | |
| 4 | age + 1 is calculated and printed | 15 | Next year you will be 16 |
The cells students fill in are left blank in this preview.
What if the user types the wrong thing?
Users type the wrong thing. They type the word ten instead of 10. Then int("ten") stops the program with a ValueError.
You can catch the error with try and except. The program does not crash. It does something else instead.