How to Print in Python with Examples
In Python, you can use the “print” function to output text or other values to the screen or a file. The syntax for the “print” function is as follows:
1 2 |
Copy code<code>print(value(s), sep=' ', end='\n', file=sys.stdout, flush=False) |
Here is a breakdown of the arguments:
value(s)
: This is the value or values that you want to print. You can pass one or more values separated by commas.sep
: This is the separator that is used between the values. The default value is a single space.end
: This is the string that is printed after all the values. The default value is a newline character.file
: This is the file object where you want to print the output. The default value is the standard output (i.e. the screen).flush
: This is a boolean value that determines whether the output is flushed (i.e. written to the file) immediately after each print statement. The default value is False.
Here are some examples of using the “print” function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Copy code<code># Print a string print("Hello, World!") # Print multiple values print("Hello", "World!") # Print values separated by a comma print("Hello", "World!", sep=", ") # Print values without a newline at the end print("Hello", "World!", end='') # Print values to a file with open('output.txt', 'w') as f: print("Hello, World!", file=f) |
In Python 3, the “print” function is a function, not a statement, so you need to use parentheses around the values that you want to print. In Python 2, the “print” statement is used instead of the “print” function, and you don’t need to use parentheses.