Basic Usage of print()
The print()
function outputs the specified message to the screen. It is often used for debugging to display the values of variables and program status during code execution.
Printing Simple Messages
print("Hello, World!")
Printing the Value of Variables
= 10
x = 20
y print(x)
print(y)
Combining Text and Variables
You can combine text and variables in the print()
function to make the output more informative. Here are 4 different ways:
This is a note.
Make sure to check your data types before processing.
1. Using Comma Separation
= "Alice"
name = 30
age print("Name:", name, "Age:", age)
2. Using String Formatting
f-string (Formatted String Literal) - Python 3.6+ [PREFERRED]
= "Bob"
name = 25
age print(f"Name: {name}, Age: {age}")
format()
Method [CAN BE USEFUL IN COMPLICATED PRINT STATEMENTS]
= "Carol"
name = 22
age print("Name: {}, Age: {}".format(name, age))
Old %
formatting [NOT RECOMMENDED]
= "Dave"
name = 28
age print("Name: %s, Age: %d" % (name, age))
Debugging with Print
Use print()
to display intermediate values in your code to understand how data changes step by step.
Example: Debugging a Loop
for i in range(5):
print(f"Current value of i: {i}")
Example: Checking Function Outputs
def add(a, b):
= a + b
result print(f"Adding {a} + {b} = {result}")
return result
5, 3) add(