Handling Input and Output in Python
A program becomes truly interactive when it can communicate with the user. This involves two fundamental operations: output, displaying information to the user, and input, receiving information from the user. Python provides simple, powerful built-in functions for both.
Output: Displaying Information with print()
The print()
function is your primary tool for showing text, variables, and results on the console.
Pyground
Display a welcome message and the value of a variable.
Expected Output:
Welcome to the world of Python!\nWe are currently on planet: Earth
Output:
Customizing print()
with sep
and end
The print()
function has optional parameters that give you more control over the output.
sep
: The separator to use between multiple items. The default is a single space (' '
).end
: The character(s) to print at the very end. The default is a newline character ('\\n'
), which moves the cursor to the next line.
Pyground
Use `sep` to join items with a comma and `end` to finish the line with a period.
Expected Output:
one, two, three\nThis is the first part... and this is the second part.
Output:
Formatting Strings for Output
Simply printing variables can be limiting. Python offers several ways to format strings, with f-strings being the modern and preferred method.
f-Strings (Formatted String Literals) were introduced in Python 3.6. They are the most readable and concise way to embed expressions inside strings. You simply prefix the string with an f
and place your variables or expressions inside curly braces {}
.
Pyground
Use an f-string to create a summary sentence.
Expected Output:
Alice is a 30-year-old Data Scientist.\nIn 5 years, she will be 35 years old.