Data Input/Output
Learn how to display output using print() and receive user input using input().
Data Input/Output
In this section, we will learn how to write programs that interact with the user — receiving input and displaying output.
Outputting Data with print()
We already met print() in the previous module. Let's look at it more closely:
By default, print() separates multiple values with a space and adds a newline at the end.
sep= and end=
You can customize both of these behaviors using the sep= and end= parameters.
sep= controls what is placed between the values:
end= controls what is printed after the last value. By default it is a newline \n, which moves the cursor to the next line. You can replace it with anything:
You can also combine both:
Variables
To store data in a program, we use variables. A variable is simply a named container that holds a value. In Python, you create a variable by writing its name, an equals sign, and the value you want to store:
From this point on, you can use the variable name anywhere in your program and Python will substitute its value.
The two most common types of variables you will encounter are numbers (like 42 or 3.14) and strings (like "Alice"). Numbers are used for calculations, while strings represent text and behave very differently — for example, 2 + 2 gives 4, but "2" + "2" gives "22".
Python is dynamically typed — you don't need to declare a variable's type, Python figures it out automatically. We will cover variables, naming rules, and data types in much more detail in the upcoming modules.
Receiving Input with input()
To receive data from the user, Python uses the input() function. It pauses the program and waits for the user to type something and press Enter:
You can pass a prompt string to input(), which will be displayed to the user before they type.
Important: input() Always Returns a String
This is a common source of mistakes. Whatever the user types, input() returns it as a string — even if they type a number:
Type Conversion
To work with numbers, you need to convert the input using int() or float():
Use int() for whole numbers and for decimal numbers: