Input and output functions let Python programs communicate with users and move data through a program. They allow you to display information, collect user input, and convert data types for calculations.
The two main tools here are print() for output and input() for user input. Once you can customize output, store input, and convert data types, you can build more interactive programs.
Input and Output Functions
Custom output with print()
print()displays output to the console (stdout)- Separates arguments with a space by default and ends with a newline character
- Customize the separator using the
sepparameterprint("Hello", "world", sep="-")outputs "Hello-world"
- Customize the line ending using the
endparameterprint("Hello", end="")outputs "Hello" without a newlineprint("Hello", end=" ")outputs "Hello " with a space instead of a newline
- Use escape characters to include special characters
\nfor newline,\tfor tabprint("Hello\nworld")outputs "Hello" on one line and "world" on the next
_function_custom_output_examples_with_sep_end_parameters_and_escape_characters%22-image-17.png)
User input and variable storage
input()gets input from the user via the console (stdin)- Prompts the user to enter a value and waits for input
- Returns the user's input as a string
- Assign the result of
input()to a variable to store the user's inputname = input("Enter your name: ")prompts the user and stores the input inname
- Provide a prompt message as an argument to guide the user
- Displayed before the user enters their input
age = input("Enter your age: ")prompts with "Enter your age: "
_function_custom_output_examples_with_sep_end_parameters_and_escape_characters%22-1035.1641649875.png)
Data type conversion for calculations
- User input is always returned as a string by
input() - Convert the input to the appropriate data type for numerical operations
int()converts input to an integernum = int(input("Enter a number: "))converts input to integer and stores innum
float()converts input to a floating-point numberprice = float(input("Enter the price: "))converts input to float and stores inprice
- Attempting numerical operations on strings will result in a
TypeErrorresult = "10" + 5raises an error (cannot add string and integer)
- Handle invalid input by catching exceptions with a
try-exceptblock- Catch
ValueErrorexceptions when converting input to numerical data types - Example:
</>Python
try: age = int(input("Enter your age: ")) except ValueError: print("Invalid input. Please enter a valid integer.")
- Catch
Advanced I/O Operations
- File I/O allows reading from and writing to files on the system
- Buffering can improve performance by reducing the number of I/O operations
- Formatting options enable precise control over output appearance