Print function is one of the fundamental building blocks in Python. This topic matters because it allows you to display output on your console and visualize the results of your code operations. In this lesson, you'll learn how to use the print function effectively, understand its features, and avoid common mistakes.
The print()
function is used to output text or variables to the console. You can pass multiple arguments to a single print()
call, which will be separated by spaces by default.
print("Hello, World!") # Output: Hello, World!
print(1 + 2) # Output: 3
print("Result:", 1 + 2) # Output: Result: 3
By default, the print function appends a newline character (\n
) at the end of each line. You can use the end
parameter to change this behavior, such as when you want to print multiple values on the same line:
print("First name:", "John", end=" ")
print("Last name:", "Doe") # Output: First name: John Last name: Doe
Similarly, use the sep
parameter to customize the separator between arguments:
print(["Apple", "Banana", "Cherry"], sep=", ") # Output: Apple, Banana, Cherry
Here are some examples of using the print function in real-world scenarios:
my_list = ["Apple", "Banana", "Cherry"]
print("Fruits:", my_list) # Output: Fruits: ['Apple', 'Banana', 'Cherry']
pi = 3.14159265
print("Pi to 4 decimal places:", round(pi, 4)) # Output: Pi to 4 decimal places: 3.1416
What causes it: Using an undefined variable in your code.
print(undefined_variable)
Error message:
Traceback (most recent call last):
File "example.py", line 5, in <module>
print(undefined_variable)
NameError: name 'undefined_variable' is not defined
Solution: Define the variable before using it in your code.
Why it happens: You haven't assigned a value to the variable.
How to prevent it: Always check that you have defined all necessary variables before trying to use them.
What causes it: Passing an incorrect data type as an argument to the print function.
print(1 + "2")
Error message:
Traceback (most recent call last):
File "example.py", line 5, in <module>
print(1 + "2")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Solution: Ensure that all arguments passed to the print function have compatible data types.
Why it happens: You are trying to perform an operation between incompatible data types (e.g., adding a number and a string).
How to prevent it: Make sure you are using the correct data types for arithmetic operations and ensure that you pass appropriate arguments to the print function.
end
and sep
parameters judiciously to format your output as needed.print()
function is used to display output on the console.print()
call, which will be separated by spaces by default.end
parameter to change the endline behavior and the sep
parameter to customize the separator between arguments.Next steps for learning: Learn about data structures like lists and dictionaries in Python, or explore advanced topics such as modules and functions.