In Python, the "print()" function is a built-in function that is used to display output on the screen. The function takes one or more arguments, which can be variables, strings, or expressions, and displays them on the console or standard output.
The "print()" function is a very useful function in Python, especially for debugging purposes and for displaying output to the user. Let's take a look at some examples to understand the usage of the "print()" function in Python:
Example 1: Displaying a string
|
print("Hello, World!")
|
In this example, we are using the "print()" function to display the string "Hello, World!" on the console. The function takes the string as an argument and displays it on the screen.
Example 2: Displaying variables
|
x = 10
y = 20
print(x + y)
|
In this example, we are using the "print()" function to display the result of adding two variables, x and y. The function takes the expression "x + y" as an argument and displays the result, which is 30, on the console.
Example 3: Displaying formatted output
|
name = "John"
age = 30
print("My name is {} and I am {} years old".format(name, age))
|
In this example, we are using the "print()" function to display a formatted string that includes variables. The function takes a string with placeholders "{}" and uses the "format()" method to substitute the placeholders with the values of the variables "name" and "age". The resulting string is then displayed on the console.
Example 4: Redirecting output to a file
|
with open("output.txt", "w") as f:
print("Hello, World!", file=f)
|
In this example, we are using the "print()" function to redirect the output to a file instead of the console. The function takes the string "Hello, World!" as an argument and writes it to a file named "output.txt" using the "with" statement and the "open()" function. The output will not be displayed on the console but will be written to the file instead.
In conclusion, the "print()" function in Python is a very useful built-in function that allows us to display output on the screen or redirect it to a file. This function can be used to display strings, variables, expressions, and formatted output, and is essential for debugging, logging, and user interaction.