The print() function in Python has several key features that make it versatile for outputting data. Here are the main features:
-
Basic Output: It can display strings, numbers, and other data types directly to the console.
print("Hello, World!") # Outputs: Hello, World! -
Multiple Arguments: You can pass multiple items to
print(), and it will automatically add spaces between them.print("The answer is", 42) # Outputs: The answer is 42 -
String Formatting: Using f-strings (formatted string literals) allows for embedding expressions inside string literals for cleaner output.
name = "Alice" age = 30 print(f"{name} is {age} years old.") # Outputs: Alice is 30 years old. -
Custom Separator: The
sepparameter allows you to specify a custom string to separate multiple items.print("Hello", "World", sep="-") # Outputs: Hello-World -
Custom End Character: The
endparameter lets you define what character to print at the end of the output, instead of the default newline.print("Hello", end="!") # Outputs: Hello! -
Output to File: You can redirect the output to a file using the
fileparameter.with open('output.txt', 'w') as f: print("Hello, File!", file=f) # Writes to output.txt
These features make print() a powerful tool for displaying information in Python programs. If you have any more questions or need examples, feel free to ask!
