Interacting with the user via the console is a fundamental part of writing terminal scripts and CLI applications.
1. input() function
Python allows for command line input. That means we are able to ask the user for input.
The method is input() (in Python 2.x it was raw_input()).
username = input("Enter username: ")
print("Username is: " + username)
Important: The input() function always returns a string. If you expect the user to enter a number to do math, you must explicitly cast it.
age = input("Enter your age: ")
# Convert to integer
age_int = int(age)
print(f"Next year you will be {age_int + 1}")
2. print() function (sep, end, flush)
You are already familiar with the print() function, which outputs data to the standard output device (the screen).
However, print() has a few hidden parameters that are very useful:
sep (Separator)
Specify how to separate the objects, if there is more than one. Default is a space ' '.
print("apple", "banana", "cherry")
# Outputs: apple banana cherry
print("apple", "banana", "cherry", sep="-")
# Outputs: apple-banana-cherry
end
Specify what to print at the end. Default is '\n' (line feed/newline).
# Prints on two lines
print("Hello")
print("World")
# Prints on the same line
print("Hello", end=" ")
print("World")
# Outputs: Hello World
flush
A boolean, specifying if the output is flushed (True) or buffered (False). Default is False. This is useful when you are printing progress bars and need the terminal to update immediately.
3. Formatting output
We covered string formatting earlier, but it is deeply tied to I/O.
When printing out variables to the user, the modern f-string approach is highly recommended. You can also perform inline calculations and formatting inside the f-string.
price = 49.99
tax = 0.05
# Display price with exactly 2 decimal places
print(f"The total cost is: ${price + (price * tax):.2f}")
The :.2f modifier tells Python to format the floating point number to 2 decimal places.
Discussion
Loading comments...