Handling Input and Output in Python
A program truly comes alive when it can communicate with you. This involves two essential processes: output (how the program displays information on the screen) and input (how the program gets information from you).
Python makes both of these operations incredibly straightforward. Let us explore how they work!
Output with print()
Output: Displaying Information with print()
The print() function is your primary way to display text, numbers, calculations, and variables on the screen. Let us see a live, interactive example:
Example
Output:
Welcome to the world of Python!We are currently on planet: Earth
Customizing print() with sep and end
By default, print() separates multiple items with a space, and automatically starts a new line at the end of each print statement. You can customize this behavior using two optional parameters:
sep: Changes the separator between multiple items (default is a single space).end: Changes what is printed at the very end of the line (default is a newline, which moves the cursor to the next line).
Let us see how they work in our interactive console:
Example
Output:
one, two, threeThis is the first part... and this is the second part.
Formatting Strings for Output
To build dynamic sentences combining text and variables, Python provides three popular formatting styles. F-strings are the modern standard and highly recommended.
f-Strings (Recommended)
f-Strings (Formatted String Literals)
Introduced in Python 3.6, f-strings are the cleanest and most readable way to build formatted text. You prefix your string with an f and place variables or math calculations directly inside curly braces {}.
Example
Output:
Alice is a 30-year-old Data Scientist.In 5 years, she will be 35 years old.