Understanding the print() Function in Python: Syntax, Parameters, and Formatting
This article explains Python's print() function, covering its syntax, parameters, usage differences between Python 2 and 3, formatting options, controlling line endings, and practical code examples for printing various data types in simple scripts.
The print() function is the most common way to output data in Python. In Python 3 it is a built‑in function, while in Python 2 it behaved as a statement.
Syntax: print(*objects, sep=' ', end='\n', file=sys.stdout) Parameters: - objects: one or more objects to be printed, separated by commas. - sep: string inserted between objects (default is a single space). - end: string appended after the last object (default is a newline). - file: a file‑like object to receive the output (default is sys.stdout).
Examples of printing different data types:
print(1) # 1<br/>print("Hello World") # Hello World<br/>x = 12<br/>print(x) # 12<br/>s = 'Hello'<br/>print(s) # Hello<br/>L = [1, 2, 'a']<br/>print(L) # [1, 2, 'a']<br/>t = (1, 2, 'a')<br/>print(t) # (1, 2, 'a')<br/>d = {'a': 1, 'b': 2}<br/>print(d) # {'a': 1, 'b': 2}Formatted output using the C‑style % operator:
s = 'Hello'<br/>x = len(s)<br/>print("The length of %s is %d" % (s, x)) # The length of Hello is 5Common format specifiers include:
d, i → signed decimal integer<br/>o → unsigned octal<br/>u → unsigned decimal<br/>x, X → unsigned hexadecimal (lower/upper case)<br/>e, E → scientific notation (lower/upper case)<br/>f, F → decimal floating point<br/>g, G → uses %e or %f depending on value<br/>c → single character<br/>r → repr() of object<br/>s → str() of objectControlling line endings (preventing the default newline):
for x in range(10):
print(x, end='') # 0123456789String concatenation example and a common mistake:
x = "Hello"
y = "world"
print(xy) # NameError: name 'xy' is not defined
print(x + y) # HelloworldSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
