2025年6月9日月曜日

How to use print() statement in Python programming

 The print() function in Python is one of the most fundamental and frequently used built-in functions. Its primary purpose is to display output to the console (standard output).

Here's a comprehensive guide on how to use print():

1. Basic Usage: Printing Strings and Numbers

You can print strings (text) enclosed in single (') or double (") quotes, and numbers directly.

Python
print("Hello, World!")        # Printing a string
print('Python is fun.')      # Also printing a string
print(123)                   # Printing an integer
print(3.14159)               # Printing a float

2. Printing Variables

You can print the values stored in variables.

Python
name = "Alice"
age = 30
pi = 3.14

print(name)
print(age)
print(pi)

3. Printing Multiple Items (Comma Separated)

You can print multiple items by separating them with commas. By default, print() will place a space between each item.

Python
name = "Bob"
age = 25

print("My name is", name, "and I am", age, "years old.")
# Output: My name is Bob and I am 25 years old.

4. Changing the Separator (sep argument)

The sep argument allows you to specify what character(s) should be used to separate the items. The default is a single space ' '.

Python
print("apple", "banana", "cherry")
# Output: apple banana cherry

print("apple", "banana", "cherry", sep=", ")
# Output: apple, banana, cherry

print("user", "name", "example", sep="@")
# Output: user@name@example

print(10, 20, 30, sep="-")
# Output: 10-20-30

5. Changing the End Character (end argument)

By default, print() adds a newline character (\n) at the end of its output, meaning subsequent print() calls will start on a new line. The end argument lets you change this behavior.

Python
print("This is line 1.")
print("This is line 2.")
# Output:
# This is line 1.
# This is line 2.

print("This will stay on the same line", end=" ")
print("as this.")
# Output: This will stay on the same line as this.

print("Item 1", end="--")
print("Item 2", end="--")
print("Item 3")
# Output: Item 1--Item 2--Item 3

6. Formatting Output (f-strings, .format(), % operator)

While comma separation is simple, for more complex or controlled formatting, you'll often use string formatting methods.

a) f-strings (Formatted String Literals) - Recommended for Python 3.6+

f-strings are concise, readable, and efficient. You prefix the string with f or F and embed expressions directly within curly braces {}.

Python
name = "Charlie"
score = 95.5

print(f"Player: {name}, Score: {score}")
# Output: Player: Charlie, Score: 95.5

# You can also include expressions
print(f"The sum of 5 and 7 is {5 + 7}.")
# Output: The sum of 5 and 7 is 12.

# Formatting numbers
price = 19.99
print(f"The price is ${price:.2f}") # .2f for 2 decimal places
# Output: The price is $19.99

percentage = 0.75
print(f"Completion: {percentage:.0%}") # .0% for percentage with no decimals
# Output: Completion: 75%

b) .format() Method (Older but still widely used)

The .format() method uses placeholders {} in the string, and then you pass the values to the .format() method.

Python
name = "David"
age = 40

print("My name is {} and I am {} years old.".format(name, age))
# Output: My name is David and I am 40 years old.

# You can use positional arguments
print("My name is {0} and I am {1} years old. {0} is a nice name.".format(name, age))
# Output: My name is David and I am 40 years old. David is a nice name.

# You can use keyword arguments
print("My name is {n} and I am {a} years old.".format(n=name, a=age))
# Output: My name is David and I am 40 years old.

c) % Operator (Oldest method, less common in new code)

This is similar to C-style printf. It's generally less preferred in modern Python due to f-strings and .format() being more readable and flexible.

Python
name = "Eve"
height = 1.75

print("Name: %s, Height: %.2f meters." % (name, height))
# %s for string, %f for float (%.2f for 2 decimal places)
# Output: Name: Eve, Height: 1.75 meters.

7. Printing None

The None keyword represents the absence of a value. When printed, it outputs "None".

Python
result = None
print(result)
# Output: None

8. Printing Empty Lines

Calling print() with no arguments will print an empty line.

Python
print("First line.")
print() # Prints an empty line
print("Third line.")
# Output:
# First line.
#
# Third line.

9. Printing to a File (Redirecting Output)

You can redirect the output of print() to a file instead of the console using the file argument.

Python
# Open a file in write mode
with open("output.txt", "w") as f:
    print("This message will go into the file.", file=f)
    print("So will this one.", file=f)

# After running this, check the 'output.txt' file in your directory.

Summary of print() arguments:

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

  • *objects: The items to be printed. You can pass zero or more objects.
  • sep=' ': String inserted between values, default a space.
  • end='\n': String appended after the last value, default a newline.
  • file=sys.stdout: An object with a write() method; defaults to the current sys.stdout (the console).
  • flush=False: If True, the stream is forcibly flushed. Useful for ensuring output appears immediately in certain situations, especially when dealing with long-running processes or debugging.

The print() function is incredibly versatile and a cornerstone of debugging and displaying information in Python programs. Mastering its various uses is essential for any Python developer.

0 件のコメント:

コメントを投稿