Basic Output in Python
In Python, the print() function serves as the primary method for displaying data. Below are fundamental output examples demonstrating various techniques for presenting strings, numbers, and formatted content.
Basic Output Examples
# Direct string output
print("Welcome to Python programming!")
# Numeric output
print(100)
print(2.71828)
# Multiple parameter output
total = 150
count = 5
print(f"Total: {total}, Items: {count}")
String Formatting Techniques
Method 1: Using format() Function
# Variable insertion
first_name = "David"
last_name = "Johnson"
age = 28
print("Name: {} {}, Age: {}".format(first_name, last_name, age))
# Numeric formatting
temperature = 98.6
print("Body temperature: {:.1f}°F".format(temperature)) # One decimal place
Method 2: f-strings (Python 3.6+)
product = "Laptop"
price = 999.99
stock = 15
print(f"Product: {product}, Price: ${price:.2f}, Stock: {stock}")
# Complex expression calculation
a = 5
b = 10
print(f"Sum: {a + b}, Product: {a * b}")
Method 3: Advanced format() Usage
# Positional specification
data = ["Python", "3.9", "Programming"]
print("Language: {}, Version: {}, Topic: {}".format(*data))
# Dictionary-based formatting
employee = {"id": 101, "name": "Sarah Miller", "department": "Engineering"}
print("Employee ID: {}, Name: {}, Department: {}".format(
employee["id"], employee["name"], employee["department"]))
Handling User Input
When accepting user input and converting to numeric types, proper error handling is essential. The following example demonstrates safe input conversion:
def get_integer_input(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Invalid input. Please enter a whole number.")
# Usage
user_number = get_integer_input("Enter your favorite number: ")
print(f"Your selected number is: {user_number}")
String Case Conversion
Python provides built-in methods to change the case of strings:
def demonstrate_case_conversion():
sample_text = "tHe QUICK broWn FOX"
# Convert to all lowercase
lowercase_version = sample_text.lower()
# Convert to all uppercase
uppercase_version = sample_text.upper()
# Convert to title case
title_case_version = sample_text.title()
# Display results
print(f"Original: {sample_text}")
print(f"Lowercase: {lowercase_version}")
print(f"Uppercase: {uppercase_version}")
print(f"Title Case: {title_case_version}")
demonstrate_case_conversion()
String Manipulation Methods
replace() vs strip()
These methods serve different purposes in string processing:
# replace() method
original_text = "Hello beautiful world"
modified_text = original_text.replace("beautiful", "wonderful")
print(f"After replace: {modified_text}")
# strip() method
messy_text = " Extra spaces around this text "
cleaned_text = messy_text.strip()
print(f"After strip: '{cleaned_text}'")
# Custom character removal
url = "https://www.example.com/"
clean_url = url.strip("/https://.:com")
print(f"Cleaned URL: {clean_url}")
String Splitting
The split() method divides strings into substrings based on specified delimiters:
# Default splitting (whitespace)
sentence = "Python is a versatile programming language"
words = sentence.split()
print(f"Words: {words}")
# Custom delimiter
csv_data = "apple,banana,cherry,date,fig"
fruits = csv_data.split(",")
print(f"Fruits list: {fruits}")
# Limited splitting
path = "home/user/documents/projects/python"
path_parts = path.split("/", 2) # Split only first two occurrences
print(f"Path parts: {path_parts}")
List Operations
Insertion
The insert() method adds elements at specified positions:
numbers = [10, 20, 30, 40, 50]
numbers.insert(2, 25) # Insert 25 at index 2
print(f"After insertion: {numbers}")
# Inserting beyond current length
colors = ["red", "blue"]
colors.insert(5, "green") # Automatically fills gaps
print(f"Color list: {colors}")
Sorting
Python offers two approaches to sorting lists:
# In-place sorting with sort()
data = [34, 12, 7, 23, 56, 8, 19]
data.sort() # Modifies original list
print(f"Sorted in-place: {data}")
# Creating new sorted list with sorted()
original_data = [34, 12, 7, 23, 56, 8, 19]
sorted_data = sorted(original_data) # Returns new list
print(f"Original: {original_data}")
print(f"New sorted: {sorted_data}")
# Reverse sorting
data.sort(reverse=True)
print(f"Reverse sorted: {data}")
Reverse Iteration
The reversed() function creates reverse iterators for sequences:
# Working with a list
sequence = [1, 2, 3, 4, 5]
reverse_iter = reversed(sequence)
# Converting to list
reverse_list = list(reverse_iter)
print(f"Original: {sequence}")
print(f"Reversed: {reverse_list}")
# Iterating in reverse
print("Reverse iteration:")
for item in reversed(sequence):
print(item, end=" ")
print()
# With strings
text = "Python"
print(f"Original string: {text}")
print(f"Reversed string: {''.join(reversed(text))}")