Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- Set Comprehensions
- String Formatting
- Indexing and Slicing
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Object-Oriented Programming (OOP)
- Object-Oriented Programming
- Classes and Objects
- the `__init__()` Constructor
- Instance Variables and Methods
- Class Variables and `@classmethod`
- Encapsulation and Data Hiding
- Inheritance and Subclasses
- Method Overriding and super()
- Polymorphism
- Magic Methods and Operator Overloading
- Static Methods
- Abstract Classes and Interfaces
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
Printing Output (print()
)
One of the first things you learn in Python is how to print output using the print()
function. It is a fundamental function that allows programmers to display text, variables, and formatted content on the console.
Although print()
may seem simple at first, it has many powerful features that make it a useful tool for debugging, displaying formatted output, and interacting with users. In this guide, we will explore the print()
function in depth, covering its syntax, formatting options, escape sequences, and advanced use cases.
1. Understanding the print()
Function
Basic Syntax
The print()
function in Python is used to output text or other values to the console. Its basic syntax is:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Parameters of print()
Parameter | Description |
---|---|
value | The data to be printed (strings, numbers, variables, etc.). |
sep | Separator used between multiple values (default: space " " ). |
end | Defines what is printed at the end (default: new line "\n" ). |
file | Where to print the output (default: sys.stdout , i.e., console). |
flush | Whether to forcibly flush the stream (default: False ). |
Simple Examples
print("Hello, World!") # Output: Hello, World!print(10) # Output: 10print(3.14) # Output: 3.14
2. Printing Multiple Arguments
You can print multiple values in a single print()
statement by separating them with commas.
name = "Alice"age = 25print("Name:", name, "Age:", age)
Output:
Name: Alice Age: 25
By default, Python separates multiple arguments with a space (" "
).
Changing the Separator (sep
parameter)
The sep
parameter allows you to change the separator between multiple values.
print("apple", "banana", "cherry", sep=", ")
Output:
apple, banana, cherry
3. Controlling the End of the Print Output (end
parameter)
By default, print()
adds a new line ("\n"
) at the end of the output. You can change this using the end
parameter.
print("Hello", end=" ")print("World!")
Output:
Hello World!
Here, "Hello"
and "World!"
are printed on the same line because end=" "
was used instead of a new line.
4. Using Escape Sequences in print()
Escape sequences allow you to insert special characters inside strings.
Escape Sequence | Description |
---|---|
\n | New line |
\t | Tab space |
\' | Single quote |
\" | Double quote |
\\ | Backslash |
Examples of Escape Sequences
print("Hello\nWorld") # New lineprint("Python\tProgramming") # Tab spaceprint("She said, \"Hello!\"") # Double quotes inside a stringprint("C:\\Users\\Alice") # Backslash
Output:
HelloWorldPython ProgrammingShe said, "Hello!"C:\Users\Alice
5. Formatting Strings in print()
Python provides several ways to format output for better readability.
1. Using f-strings (Python 3.6+)
name = "Alice"age = 25print(f"My name is {name} and I am {age} years old.")
Output:
My name is Alice and I am 25 years old.
2. Using .format()
Method
print("My name is {} and I am {} years old.".format(name, age))
3. Using %
Formatting (Old Method)
print("My name is %s and I am %d years old." % (name, age))
6. Printing Lists and Dictionaries
Python allows you to print complex data structures like lists and dictionaries.
Printing Lists
fruits = ["apple", "banana", "cherry"]print(fruits)
Output:
['apple', 'banana', 'cherry']
Printing Dictionaries
person = {"name": "Alice", "age": 25}print(person)
Output:
{'name': 'Alice', 'age': 25}
7. Printing to a File (file
parameter)
You can redirect print()
output to a file instead of the console.
with open("output.txt", "w") as file: print("Hello, World!", file=file)
This will create a file output.txt
with the content:
Hello, World!
8. Printing Without a New Line in a Loop
If you want to print output on the same line in a loop, you can use end=" "
.
for i in range(5): print(i, end=" ")
Output:
0 1 2 3 4
9. Using flush=True
for Immediate Output
By default, Python buffers print statements. To flush output immediately, use flush=True
.
import timefor i in range(5): print(i, end=" ", flush=True) time.sleep(1)
This ensures that each number is printed immediately without buffering.
10. Debugging with print()
The print()
function is useful for debugging programs.
x = 10y = 20print(f"Debugging: x = {x}, y = {y}")
Output:
Debugging: x = 10, y = 20