Python
#1
TIOBE#1
PYPL#1
GitHub#4
RedMonk#2
IEEESpectrum#1
JetBrains#2
Programming Language
Python
Overview
Python is a general-purpose programming language with simple and readable syntax.
Details
Python is an interpreted programming language developed by Guido van Rossum in 1991, characterized by a design philosophy that emphasizes "code readability." With its rich standard library and vast third-party package ecosystem, Python is utilized across a wide range of fields from data analysis and machine learning to web development, desktop applications, and system administration. Its indentation-based block structure and simple grammar make it accessible to programming beginners while maintaining the flexibility to handle large-scale systems.
Code Examples
Hello World
# Basic output
print("Hello, World!")
# Output using variables
message = "Hello, Python!"
print(message)
# Output using format strings
name = "John"
age = 25
print(f"My name is {name} and I am {age} years old.")
File I/O
# Writing to a file
with open("sample.txt", "w", encoding="utf-8") as file:
file.write("This is a test file.\n")
file.write("Learning file operations in Python.")
# Reading from a file
with open("sample.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
# Reading line by line
with open("sample.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip()) # Remove newline characters
Conditional Statements
# Basic if statement
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"
print(f"Score: {score}, Grade: {grade}")
# Combining multiple conditions
age = 20
has_license = True
if age >= 18 and has_license:
print("You can drive")
elif age >= 18:
print("Please get a license")
else:
print("Please get a license after turning 18")
Lists, Dictionaries, Tuples
# List (array) operations
fruits = ["apple", "banana", "orange"]
fruits.append("grape") # Adding an element
print(f"Fruit list: {fruits}")
print(f"First fruit: {fruits[0]}")
# Dictionary (hash) operations
person = {
"name": "John Doe",
"age": 30,
"city": "Tokyo"
}
person["job"] = "Engineer" # Adding new key-value pair
print(f"Name: {person['name']}, Age: {person['age']}")
# Tuple (immutable list)
coordinates = (10, 20)
print(f"Coordinates: x={coordinates[0]}, y={coordinates[1]}")
Loops and Iteration
# Processing list elements sequentially
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(f"Number: {num}, Double: {num * 2}")
# Numeric loop using range()
for i in range(1, 6):
print(f"Square of {i} is {i**2}")
# Processing dictionary elements
student_scores = {"John": 85, "Jane": 92, "Bob": 78}
for name, score in student_scores.items():
print(f"{name}'s score: {score}")
# while loop
count = 0
while count < 5:
print(f"Count: {count}")
count += 1
Function Definition and Calling
# Basic function
def greet(name):
"""Function to greet someone"""
return f"Hello, {name}!"
# Function with default arguments
def calculate_area(width, height=10):
"""Function to calculate rectangle area"""
return width * height
# Function returning multiple values
def get_name_age():
"""Function to return name and age"""
return "John Doe", 25
# Function calls
message = greet("Alice")
print(message)
area = calculate_area(5) # height uses default value 10
print(f"Area: {area}")
name, age = get_name_age() # Tuple unpacking
print(f"Name: {name}, Age: {age}")
Class Definition and Usage
class Car:
"""Class representing a car"""
def __init__(self, make, model, year):
"""Constructor (initialization method)"""
self.make = make # Manufacturer
self.model = model # Model
self.year = year # Year
self.mileage = 0 # Mileage
def drive(self, distance):
"""Method to drive and increase mileage"""
self.mileage += distance
print(f"Drove {distance}km. Total mileage: {self.mileage}km")
def get_info(self):
"""Method to get car information"""
return f"{self.year} {self.make} {self.model}"
# Class instantiation and usage
my_car = Car("Toyota", "Prius", 2022)
print(my_car.get_info())
my_car.drive(50)
my_car.drive(30)
Library Usage
# Using standard libraries
import datetime
import random
import json
# Get current date and time
now = datetime.datetime.now()
print(f"Current time: {now.strftime('%Y-%m-%d %H:%M:%S')}")
# Generate random numbers
random_number = random.randint(1, 100)
print(f"Random number: {random_number}")
# JSON data processing
data = {
"name": "Python Learner",
"skills": ["basic syntax", "functions", "classes"],
"level": "beginner"
}
# Convert dictionary to JSON string
json_string = json.dumps(data, indent=2)
print("JSON format:")
print(json_string)
# Example of popular third-party library
# Install with: pip install requests
try:
import requests
response = requests.get("https://api.github.com/users/python")
if response.status_code == 200:
user_data = response.json()
print(f"GitHub user: {user_data['name']}")
except ImportError:
print("requests library is not installed")
Special Features
List Comprehensions
# Basic list comprehension
squares = [x**2 for x in range(1, 6)]
print(f"Squares of 1-5: {squares}")
# Conditional list comprehension
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(f"Even squares: {even_squares}")
Decorators
def timer(func):
"""Decorator to measure function execution time"""
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} execution time: {end - start:.4f}s")
return result
return wrapper
@timer
def slow_function():
"""Sample time-consuming process"""
import time
time.sleep(1)
return "Processing complete"
result = slow_function()
Context Managers
class DatabaseConnection:
"""Example database connection context manager"""
def __enter__(self):
print("Connected to database")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Database connection closed")
def query(self, sql):
print(f"Executing: {sql}")
# Safe resource management with with statement
with DatabaseConnection() as db:
db.query("SELECT * FROM users")
Versions
Version | Status | LTS | Release Date | End of Support |
---|---|---|---|---|
Python 3.13 | Latest | - | 2024-10-07 | 2029-10 |
Python 3.12 | Current | - | 2023-10-02 | 2028-10 |
Python 3.11 | Current | - | 2022-10-24 | 2027-10 |
Python 3.10 | Current | - | 2021-10-04 | 2026-10 |
Python 3.9 | Current | - | 2020-10-05 | 2025-10 |
Python 3.8 | Security fixes only | - | 2019-10-14 | 2024-10 |
Python 2.7 | End of life | - | 2010-07-03 | 2020-01-01 |
Reference Pages
Official Documentation
- Python.org - Official site
- Python Documentation - Official documentation
- Python Tutorial - Official tutorial
Learning Resources
- Real Python - Practical Python tutorials
- Python Software Foundation - Python community
- PyPI - Python Package Index
Development Tools
- Python Package Index (PyPI) - Package repository
- Anaconda - Python distribution for data science
- Jupyter Notebook - Interactive development environment