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 print("Hello World") # Hello World x = 12 print(x) # 12 s = 'Hello' print(s) # Hello L = [1, 2, 'a'] print(L) # [1, 2, 'a'] t = (1, 2, 'a') print(t) # (1, 2, 'a') d = {'a': 1, 'b': 2} print(d) # {'a': 1, 'b': 2}
Formatted output using the C‑style % operator: s = 'Hello' x = len(s) print("The length of %s is %d" % (s, x)) # The length of Hello is 5
Common format specifiers include: d, i → signed decimal integer o → unsigned octal u → unsigned decimal x, X → unsigned hexadecimal (lower/upper case) e, E → scientific notation (lower/upper case) f, F → decimal floating point g, G → uses %e or %f depending on value c → single character r → repr() of object s → str() of object
Controlling line endings (preventing the default newline): for x in range(10): print(x, end='') # 0123456789
String concatenation example and a common mistake: x = "Hello" y = "world" print(xy) # NameError: name 'xy' is not defined print(x + y) # Helloworld
Test Development Learning Exchange
Test Development Learning Exchange
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.