Print statements

The print() function is used to display output on the screen. It allows us to show messages, variables, or the result of expressions in our code.

To use it, simply write print() followed by the content you want to display. Here's an example:

print("Hello, world!")

In this example, we use the print() function to display the message "Hello, world!" on the screen. When you run this code, you will see the output "Hello, world!" displayed on the screen.

You can also print variables by including them as arguments inside the print() function. For example:

name = "John"
age = 15
print("My name is", name, "and I am", age, "years old.")

In this code, we have two variables name and age. We use the print() function to display a message that includes the values of these variables. The output will be "My name is John and I am 15 years old."

You can also print the result of expressions or calculations. For example:

x = 5
y = 3
print("The sum of", x, "and", y, "is", x + y)

In this code, we use the print() function to display a message that includes the sum of x and y. The output will be "The sum of 5 and 3 is 8."

Additionally, you can use special characters inside the print() function to format your output. For example:

name = "John"
age = 15
print("My name is %s and I am %d years old." % (name, age))

In this code, we use the %s and %d placeholders to format the output. The %s is used for strings, and %d is used for integers. The values of name and age are passed as arguments to the % operator.

A better alternative is to use an f-string to include variables in the print function.

name = "John"
age = 15
print(f"My name is {name} and I am {age} years old.")

The print function is often used by beginners for inspecting variables while debugging code. In such cases, it can be useful to display both the variable name as well as its value. This can be done conveniently using f-strings by simply adding = to the curly brackets. For example:

name = "John"
age = 15
print(f"{name=} and {age=}")  # Output: name = 'John' and age = 15