Python Input and Output
Programs need to interact with users, receiving input from users and displaying results to users. Python provides simple and direct methods to implement input and output operations.
Getting User Input: input()
The input() function is the standard way in Python to get user input. It pauses program execution, waiting for the user to enter some text in the terminal and press Enter.
- The
input()function always returns user input as a string (str), regardless of whether the user enters numbers or other characters. - You can provide a string parameter in the
input()function as a prompt to display to the user.
Example:
Running result:
Handling Numeric Input
Since input() returns a string, if you need to perform mathematical operations on user input, you must first convert it to a numeric type (such as int or float).
If the user enters an invalid number, the int() or float() conversion will raise a ValueError. In practical applications, you usually need to use try-except statements to handle such potential errors.
Outputting to Screen: print()
The print() function is our most commonly used output tool; it can print one or more objects to the console.
Advanced Usage of print()
The print() function has two very useful optional parameters: sep and end.
-
sep(separator): Used to specify the character used to separate multiple output objects. Default is a space' '. -
end: Used to specify the character to add at the end after all content is printed. Default is a newline\n.
By combining f-strings with the sep and end parameters of the print() function, you can precisely control the output format of your program.