Input and output functions are essential for interacting with users and managing data flow in Python programs. These functions allow you to display information, collect user input, and convert data types for calculations.
Understanding how to use print() and input() effectively is crucial for creating interactive programs. You'll learn to customize output, handle user input, and convert data types to perform operations, laying the foundation for more complex programming tasks.
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
sep
parameterprint("Hello", "world", sep="-")
outputs "Hello-world"
- Customize the line ending using the
end
parameterprint("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
\n
for newline,\t
for tabprint("Hello\nworld")
outputs "Hello" on one line and "world" on the next
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: "
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
TypeError
result = "10" + 5
raises an error (cannot add string and integer)
- Handle invalid input by catching exceptions with a
try-except
block- Catch
ValueError
exceptions when converting input to numerical data types - Example:
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