Language Overview
Python is favored for its readability and extensive ecosystem, particularly in data science and AI. It supports dynamic typing and comes with built-in structures that simplify development. Always target Python 3.x as version 2 is deprecated.
Fundamental Operations
Input and Output
Standard interaction involves the input function for user data and print for display. The input returns a string type by default, requiring explicit conversion for numerical operations.
def capture_user_data():
username = input("Enter your identifier: ")
print(f"Welcome, {username}")
Variables and Naming
Variables hold references to objects without needing explicit declaration. Naming conventions should follow snake_case. Special prefixes like underscores indicate internal usage.
user_count = 10
_is_internal_flag = True
PI_VALUE = 3.14159 # Constants are typically uppercase
Comments and Documentation
Code explanation is achieved via single-line comments or docstrings within functions. Docstrings define behavior but remain part of the object metadata.
def calculate_area(length, width):
\"\"\"Returns the area of a rectangle.\"\"\"
return length * width
# This line explains the next logic
result = calculate_area(5, 2)
Data Structures
Python provides robust containers for organizing data.
Lists and Tuples
Lists are mutable sequences denoted by brackets [], while tuples () are immutable.
inventory = ["laptop", "charger"]
inventory.append("mouse") # Valid
coordinates = (10, 20) # coordinates[0] = 15 raises an error
Sets and Dictionaries
Sets store unique unordered items {}. Dictionaries map keys to values {key: value}.
unique_ids = {101, 102, 102} # Result: {101, 102}
user_profile = {"name": "Alex", "role": "Admin"}
To convert between types or check existence:
data = set([1, 2, 3])
is_present = "item" in data
Control Flow Logic
Conditional execution relies on comparison operators. Since Python 3.10, match-case offers structured pattern matching alternatives to complex if-elif chains.
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
Loops iterate over sequences using for or condition checks with while. The break and continue statements control iteration flow.
for i in range(10):
if i == 3:
continue
print(i)
String manipulation supports slicing [start:stop] wich excludes the stop index.
text = "Programming"
sub = text[1:3] # 'ro'
reversed_sub = text[::-1]
Function Design
Functions encapsulate logic to promote reusability. Parameters allow data passage, while optional arguments provide defaults.
def greet(name="Guest"):
return f"Hello, {name}"
def process_args(*args):
for item in args:
print(item)
Variable scope distinguishes between local definitions inside a function and global ones outside. Use the global keyword sparingly to modify outer scope variables.
Modules and File Handling
External functionality is accessed via import statements. Files are managed using context managers (with) to ensure proper closure.
import json
def read_config(path):
with open(path, "r") as f:
return json.load(f)
Text files support modes like read (r), write (w), and append (a). CSV and JSON require dedicated parsing libraries (csv, json).
Error Management
Robust applications handle exceptions gracefully using try-except-finally blocks. Assertions verify assumptions during development.
try:
number = int(input("Enter integer: "))
except ValueError:
print("Invalid format provided")
else:
print(f"Calculated square: {number ** 2}")
finally:
print("Execution finished")
Common errors include ValueError for bad casting and KeyError for missing dictionary entries.
Practical Integration Example
The following example demonstrates combining lists, loops, and conditions in a game logic scenario.
board_state = [" "] * 9
winner_map = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]
def evaluate_board(current_state):
for a, b, c in winner_map:
if current_state[a] != " " and current_state[a] == current_state[b] == current_state[c]:
return True
return " " not in current_state
player_move = 0
while player_move < 5:
move_input = int(input("Select slot [0-8]: "))
board_state[move_input] = "X"
if evaluate_board(board_state):
break
# Simple opponent simulation
opponent_slot = sum(board_state) % len(board_state)
board_state[opponent_slot] = "O"
player_move += 1
print("Game Over")