What are the different ways to use the print function i…
In Python, the print function can be operated in various ways. Here are common print operation methods:
- Print the string:
print("Hello, World!")
- Print the value of the variable:
x = 10
print(x)
- Print the values of multiple variables.
x = 10
y = 20
print(x, y)
- Formatted Output
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
- Specify the separator using the sep parameter.
x = 10
y = 20
print(x, y, sep=", ")
- Specify the end character using the end parameter.
print("Hello", end=" ")
print("World")
Output: Greetings Earth
- Redirect the output to a file:
with open("output.txt", "w") as f:
print("Hello, World!", file=f)
The above are some common printing methods, you can choose the one that suits your specific needs.