The print() Function

UpComing SoftWare Training Demos

๐Ÿš€ *Playwright With AI Testing Demo In Telugu*
๐Ÿ—“๏ธ *Date:* 28 Oct2026, 08:00 PM IST
๐Ÿ“ *Register Now!:*
https://www.vlrt.in/3r
๐Ÿ‘ฅ *Join WA Community:*
https://www.vlrt.in/3w
๐Ÿ’ก *Course Content:*
https://www.vlrt.in/3c
โ–ถ๏ธ *Demo Videos:*
https://www.vlrt.in/3v

๐Ÿš€ *Gen AI Engineer (Production Focused)*
๐Ÿ—“๏ธ *Date:* 29th Oct 2026, 06:00PM IST
๐Ÿ“ *Register Now!:*
https://www.vlrt.in/gr
๐Ÿ‘ฅ *Join WA Community:*
https://www.vlrt.in/gw
๐Ÿ’ก*Course Content:*
https://www.vlrt.in/ai
โ–ถ๏ธ *Demo Videos:*
https://www.vlrt.in/gv

๐Ÿš€ *Vulnerability Management Training Demo*
๐Ÿ—“๏ธ *Date:* 28th Oct 2026, 10:00 AM IST
๐Ÿ“*Register Now!:*
https://www.vlrt.in/vr
๐Ÿ‘ฅ *Join Community:*
https://www.vlrt.in/cw
๐Ÿ’ก *Course Content:*
https://www.vlrt.in/vc
โ–ถ๏ธ *Demo Videos:*
https://www.vlrt.in/Vm

The print() Function Syntax in Python ๐Ÿ–จ๏ธ

The basic syntax of the print() function in Python is:

Python

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Let’s break down each part:

  • print(): This is the function name.
  • *objects (positional argument, arbitrary number):
    • This represents one or more items (objects) that you want to print.
    • You can pass numbers, strings, variables, lists, dictionaries, results of expressions, etc.
    • If you pass multiple objects, they will be converted to strings and printed.
  • sep=' ' (keyword argument, optional):
    • This stands for “separator”.
    • It specifies how the objects are separated when multiple items are printed.
    • By default, it’s a single space character (' ').
    • You can change it to any string, e.g., sep=',' for comma-separated values, or sep='---' for dashes.
  • end='\n' (keyword argument, optional):
    • This specifies what to print at the end of the output.
    • By default, it’s a newline character ('\n'), which means after print() finishes, the cursor moves to the next line.
    • You can change it to an empty string (end='') to keep the cursor on the same line, or any other string.
  • file=sys.stdout (keyword argument, optional):
    • This specifies where the output should go.
    • By default, it’s sys.stdout, which means the output is sent to the standard output device (usually your console or terminal).
    • You can redirect the output to a file by providing a file object, e.g., file=my_file_object.
  • flush=False (keyword argument, optional):
    • This is a boolean argument that controls whether the output stream is forcibly flushed.
    • When True, the output is immediately written to the file.
    • When False (default), the output might be buffered, meaning it’s held in memory for a short time before being written, which can be more efficient for large outputs.

Simple Examples to Illustrate: ๐Ÿ’ก

Python

# 1. Printing a single string
print("Hello, Python!") # Output: Hello, Python!

# 2. Printing multiple objects with default separator
name = "Alice"
age = 30
print("Name:", name, "Age:", age) # Output: Name: Alice Age: 30

# 3. Changing the separator
print("Apple", "Banana", "Cherry", sep="-") # Output: Apple-Banana-Cherry

# 4. Preventing a newline at the end
print("Loading...", end="")
print("Done!") # Output: Loading...Done!

# 5. Redirecting output to a file
# with open("log.txt", "w") as f:
#     print("This message goes to a file!", file=f)
#     # This will write "This message goes to a file!" into a new file named log.txt

# 6. Printing expressions
print(2 + 3 * 4) # Output: 14

Basic print() Function in Python with Examples ๐Ÿ–จ๏ธ

The print() function is used to display output in Python. It can print text, numbers, variables, or any combination of these.


1. Simple Print Statement ๐Ÿ—ฃ๏ธ

Prints a string or number directly:

Python

print("Hello, World!")  # Output: Hello, World!
print(42)              # Output: 42

2. Printing Multiple Items ๐Ÿงฉ

Separates items with a space by default:

Python

name = "Alice"
age = 25
print("Name:", name, "Age:", age)  # Output: Name: Alice Age: 25

3. Changing the Separator (sep) โ†”๏ธ

Use sep to customize how items are separated:

Python

print("Python", "Java", "C++", sep=" | ")  # Output: Python | Java | C++

4. Preventing Line Breaks (end) โžก๏ธ

Override the default newline (\n) with end:

Python

print("Hello", end=" ")
print("World!")  # Output: Hello World!

5. Printing Special Characters โœจ

Use escape sequences for formatting:

Python

print("Line1\nLine2\tIndented")
# Output:
# Line1
# Line2    Indented

6. Printing Variables with f-strings (Python 3.6+) ๐Ÿ’ฌ

Embed variables directly in strings:

Python

name = "Bob"
print(f"Hello, {name}!")  # Output: Hello, Bob!

Key Takeaways ๐ŸŽฏ

  • Basic Syntax: print("text") or print(variable). ๐Ÿ“
  • Multiple Items: Separate with commas (default space separator). โž•
  • Custom Separators: Use sep="|" to change the delimiter. โ†”๏ธ
  • No Newline: Set end="" to print on the same line. โžก๏ธ
  • f-strings: Clean way to embed variables (Python 3.6+). โœจ

The print() function is essential for debugging and displaying results in Python! ๐Ÿš€

Here are 10 practical examples of f-strings in Python, covering basic to advanced usage: โœจ


1. Basic Variable Insertion ๐Ÿ“

Embed variables directly in strings.

Python

name = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old.")
# Output: My name is Alice and I'm 25 years old.

2. Mathematical Expressions โž•

Perform calculations inside the f-string.

Python

x = 10
y = 3
print(f"{x} + {y} = {x + y}")
# Output: 10 + 3 = 13

3. Number Formatting ๐Ÿ”ข

Control the display of numbers.

A. Round Floats ๐Ÿ”ข. Specify the number of decimal places.

Python

pi = 3.14159
print(f"Pi โ‰ˆ {pi:.2f}")  # 2 decimal places
# Output: Pi โ‰ˆ 3.14

B. Add Commas to Large Numbers ๐Ÿ’ฒ Improve readability of large numbers.

Python

population = 1_000_000
print(f"Population: {population:,}")
# Output: Population: 1,000,000

C. Percentages ๐Ÿ“ˆ Format as a percentage.

Python

ratio = 0.75
print(f"Completion: {ratio:.0%}")
# Output: Completion: 75%

4. String Alignment โ†”๏ธ

Align text within a specified width.

Python

text = "Python"
print(f"{text:>10}")  # Right-aligned (10 spaces)
print(f"{text:<10}")  # Left-aligned
print(f"{text:^10}")  # Centered
# Output:
#     Python
# Python    
#   Python  

5. Date Formatting ๐Ÿ“…

Format datetime objects.

Python

from datetime import datetime
today = datetime.now()
print(f"Today: {today:%B %d, %Y}")
# Output: Today: June 23, 2025 (or current date)

6. Dictionary Values ๐Ÿ“š

Access dictionary values directly.

Python

user = {"name": "Bob", "age": 30}
print(f"{user['name']} is {user['age']} years old.")
# Output: Bob is 30 years old.

7. Function Calls ๐Ÿ“ž

Embed function calls within the string.

Python

def greet(name):
    return f"Hello, {name}!"
print(f"{greet('Alice')}")
# Output: Hello, Alice!

8. Debugging (Python 3.8+) ๐Ÿž

Print variable name and value for quick debugging.

Python

x = 42
print(f"{x = }")  # Prints variable name and value
# Output: x = 42

9. Multiline F-Strings ๐Ÿ“œ

Create formatted multiline strings.

Python

name = "Alice"
score = 95.5
print(f"""
Name: {name}
Score: {score:.1f}/100
""")
# Output:
# Name: Alice
# Score: 95.5/100

10. Conditional Logic ๐Ÿค”

Use a ternary operator for simple conditions.

Python

age = 17
print(f"{'Adult' if age >= 18 else 'Minor'}")
# Output: Minor

Key Advantages of F-Strings โœจ

  • Readability: Embed variables/expressions directly in strings. ๐Ÿ“–
  • Performance: Faster than % formatting or .format(). ๐Ÿš€
  • Flexibility: Supports expressions, formatting, and even debugging. ๐Ÿคธ

When to Use F-Strings? ๐Ÿ’ก

  • Dynamic messages (e.g., user greetings). ๐Ÿ’ฌ
  • Formatting numbers/dates. ๐Ÿ”ข๐Ÿ“…
  • Debugging complex variables. ๐Ÿ›

F-strings make your code cleaner and more efficient! โœ…

Similar Posts

  • While loop

    A while loop in Python is used to repeatedly execute a block of code as long as a given condition remains True. It is particularly useful when you don’t know beforehand how many times the loop needs to run. Before every iteration, Python evaluates the condition. If it evaluates to True, the code inside the…

  • install Python, idle, Install pycharm

    Step 1: Download Python Step 2: Install Python Windows macOS Linux (Debian/Ubuntu) Open Terminal and run: bash Copy Download sudo apt update && sudo apt install python3 python3-pip For Fedora/CentOS: bash Copy Download sudo dnf install python3 python3-pip Step 3: Verify Installation Open Command Prompt (Windows) or Terminal (macOS/Linux) and run: bash Copy Download python3 –version # Should show…

  • Variable Length Keyword Arguments in Python

    Variable Length Keyword Arguments in Python Variable length keyword arguments allow a function to accept any number of keyword arguments. This is done using the **kwargs syntax. Syntax python def function_name(**kwargs): # function body # kwargs becomes a dictionary containing all keyword arguments Simple Examples Example 1: Basic **kwargs python def print_info(**kwargs): print(“Information received:”, kwargs) print(“Type of…

  • re.sub()

    Python re.sub() Method Explained The re.sub() method is used for searching and replacing text patterns in strings. It’s one of the most powerful regex methods for text processing. Syntax python re.sub(pattern, repl, string, count=0, flags=0) Example 1: Basic Text Replacement python import re text = “The color of the sky is blue. My favorite color is blue too.” #…

  • Finally Block in Exception Handling in Python

    Finally Block in Exception Handling in Python The finally block in Python exception handling executes regardless of whether an exception occurred or not. It’s always executed, making it perfect for cleanup operations like closing files, database connections, or releasing resources. Basic Syntax: python try: # Code that might raise an exception except SomeException: # Handle the exception else:…

  • Quantifiers (Repetition)

    Quantifiers (Repetition) in Python Regular Expressions – Detailed Explanation Basic Quantifiers 1. * – 0 or more occurrences (Greedy) Description: Matches the preceding element zero or more times Example 1: Match zero or more digits python import re text = “123 4567 89″ result = re.findall(r’\d*’, text) print(result) # [‘123’, ”, ‘4567’, ”, ’89’, ”] # Matches…

Leave a Reply

Your email address will not be published. Required fields are marked *