Computers and software don't live in isolation. They are tools that solve real-world problems, meaning they must interact with the real world. A computer needs to take input from some source, perform some actions on that input, and then provide output.
Computer programs can use many input sources, such as mice, keyboards, disks, the network, and environmental sensors. Similarly, a program can write output to multiple places, such as the screen, a log, or a network.
A computer can obtain input from another computer's output. For example, when you enter your login credentials for a website, your computer first encrypts them. It then sends them to the website's authentication server, which accepts (inputs) the data and attempts to verify your identity. In this fashion, two computers can perform different parts of a common task.
In this chapter, we'll discuss the most basic techniques a program can use to interact with the outside world: reading keyboard input and displaying output in a terminal.
You've already seen one way to display output in the terminal: the print
function. This built-in function takes any Python value, regardless of type, and prints it. Let's see an example. Create a file named greetings.py
with the following content:
name = 'Jane'
print(f'Good morning, {name}!')
In this simple example, we initialize a name
variable with the string 'Jane'
, then use it in an f-string interpolation to build and display a greeting message. Run the program to see it in action:
$ python greetings.py
Good morning, Jane!
The print()
function works with all data types, often -- but not always -- formatting the output in some manner that makes it somewhat understandable to humans. For instance:
>>> print({ 'a': 1, "b": 42, 'c': "string",
... 'd': [5, 6], 'e': { 8, 9, 10 }})
# Pretty printed for clarity
{
'a': 1,
'b': 42,
'c': 'string',
'd': [5, 6],
'e': {8, 9, 10}
}
>>> import time
>>> print(time.asctime())
Mon Aug 21 22:59:29 2023
You can print multiple objects by just listing them one after the other as arguments to print()
:
>>> print(1, 2, 3, 'a', 'b')
1 2 3 a b
>>> print([1, 2, 3], 4, False, { 5, 6, 7, 8})
[1, 2, 3] 4 False {8, 5, 6, 7}
By default, multiple items are separated by spaces. You can use a different separator with the sep
keyword argument (we discuss keyword arguments in the Core Curriculum):
print(1, 2, 3, 'a', 'b', sep=',') # 1,2,3,a,b
print('a', 'b', 'c', 'd', 'e', sep='') # abcde
Note that using an empty string as the sep
value causes all the values to be printed without separation.
The end
keyword argument defines what print()
prints after it prints the last argument. By default, it prints a newline (\n
). The most common reasons for using end
are compatibility with Windows (which sometimes needs a newline of \r\n
) and for suppressing the newline altogether. Here are two more examples:
>>> print(1, 2, 'a', 'b', sep=',', end=' <-\n')
1,2,a,b <-
>>> print('a', 'b', end='', sep=','); print('c', 'd', sep=',')
a,bc,d
Note the semicolon (;
) on line 4: that's an easy way to enter multiple statements on a single line. Mostly, you should only use semicolons like this in the REPL.
Finally, to start a new line immediately without printing anything else, just run print()
with no arguments:
>>> print()
>>>
In the previous example, we assigned a value to name
and displayed a fixed greeting message that uses that name. That's probably not the most exciting thing you've seen today. We hard-coded the name, which means the program will always use the same name. We must modify and rerun the program to greet a different person. You probably wouldn't bother using a program that worked like that.
Can we ask the user to provide her name and greet her with a message that uses the name she entered? Yes, we can. Python has a built-in function called input()
that lets Python programs read input from the terminal.
Let's use input()
to write a program that displays a personalized greeting message for the user based on the name she provides. Create a file named personalized_greeting.py
with the following code:
print("What's your name?")
name = input()
print(f'Good Morning, {name}!')
Run the program from the command line. It displays the What's your name?
question, then waits for your input. When you enter a name and hit Return, the program displays a custom greeting message:
$ python personalized_greeting.py
What's your name?
Rachele
Good Morning, Rachele!
You can also use the input()
function to display the prompt the user sees:
# highlight
name = input("What's your name? ")
# endhighlight
print(f'Good Morning, {name}!')
Note the space after the ?
: you'll see why that's needed when you run the program:
$ python personalized_greeting.py
What's your name? Rachele
Good Morning, Rachele!
See how input()
retrieved the input from the same line as the prompt? That's why we needed the extra space. Without the space, we'd see:
What's your name?Rachele
Good Morning, Rachele!
Alternatively, we can have input()
output a newline instead of a space:
# highlight
name = input("What's your name?\n")
# endhighlight
print(f'Good Morning, {name}!')
$ python personalized_greeting.py
What's your name?
Rachele
Good Morning, Rachele!
That's more like what we started with when we used print()
to display the prompt. In this code, the \n
is an escape character that the computer treats as a newline. \n
is accepted almost universally in programming languages, though the circumstances needed to produce the desired effect may vary slightly.
Let's write a program that asks for two numbers from the user, adds them, and then displays the result. Put the following code in a new file called sum_numbers.py
and then run it:
number1 = input('Enter the first number: ')
number2 = input('Enter the second number: ')
sum = number1 + number2
print(f'The numbers {number1} and {number2} '
f'add to {sum}')
$ python sum_numbers.py
Enter the first number: 2
Enter the second number: 3
The numbers 2 and 3 add to 23
Oops. Something isn't right. The program reports that the result is 23
, not 5
like we want. Where do you think the problem lies? If you said that input()
returns strings, so +
performs concatenation, you're right! Since number1
and number2
both hold string values instead of numbers, the +
operator concatenates them instead of adding them. If you want to add two variables arithmetically, both must have a numeric data type.
As we learned earlier, we can convert (coerce) strings to numbers with the int()
or float()
function. Update line 3 from sum_numbers.py
to match this code:
number1 = input('Enter the first number: ')
number2 = input('Enter the second number: ')
# highlight
sum = float(number1) + float(number2)
# endhighlight
print(f'The numbers {number1} and {number2} add to {sum}')
$ python sum_numbers.py
Enter the first number: 2
Enter the second number: 3
The numbers 2 and 3 add to 5.0
input()
still returns a string, but we've coerced each string to a float this time. With numbers on both sides of the +
, Python adds them arithmetically.
Be sure to play with these examples a bit. You can, for example, replace addition with subtraction or multiplication in the above example. Try to think of some applications of input()
on your own.
I/O (Input/Output) in Python is a complex topic requiring knowledge of concepts we haven't yet learned. They're essential concepts, but we don't discuss them in this book; we cover them in the Core Curriculum. Until then, we can use print()
and input()
to interact with users.
These examples are simple, but they demonstrate how you can obtain user input, perform some work with that input, and then use the results to show some output to the user. This input/output cycle is at the heart of every computer program. After all, software that accepts no input and provides no output is useless.
Write a program named greeter.py
. The program should ask for your name, then output Hello, NAME!
where NAME
is the name you entered:
$ python greeter.py
What is your name? Sue
Hello, Sue!
name = input('What is your name? ')
print('Hello, ' + name + '!')
name = input('What is your name? ')
print(f'Hello, {name}!')
Video Walkthrough
Modify the greeter.py
program to ask for the user's first and last names separately, then greet the user with their full name.
$ python greeter.py
What is your first name? Bob
What is your last name? Roberts
Hello, Bob Roberts!
first_name = input('What is your first name? ')
last_name = input('What is your last name? ')
print(f'Hello, {first_name} {last_name}!')
Video Walkthrough
Write a program named age.py
that asks the user to enter their age, then calculates and reports the future age 10, 20, 30, and 40 years from now. Here's the output for someone who is 27 years old.
How old are you? 27
You are 27 years old.
In 10 years, you will be 37 years old.
In 20 years, you will be 47 years old.
In 30 years, you will be 57 years old.
In 40 years, you will be 67 years old.
# This solution coerces the input age when a numeric
# age is needed. This code is repetitive.
age = input('How old are you? ')
print()
print(f'You are {age} years old.')
print(f'In 10 years, you will be {int(age) + 10} years old.')
print(f'In 20 years, you will be {int(age) + 20} years old.')
print(f'In 30 years, you will be {int(age) + 30} years old.')
print(f'In 40 years, you will be {int(age) + 40} years old.')
# This solution reduces the repetition by calling int
# once only.
age = int(input('How old are you? '))
print()
print(f'You are {age} years old.')
print(f'In 10 years, you will be {age + 10} years old.')
print(f'In 20 years, you will be {age + 20} years old.')
print(f'In 30 years, you will be {age + 30} years old.')
print(f'In 40 years, you will be {age + 40} years old.')
Video Walkthrough