Python Core Basic Syntax and Practical Operation Examples
western_zodiac_signs = ("Capricorn", "Aquarius", "Pisces", "Aries", "Taurus", "Gemini",
"Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius")
sign_cutoff_dates = ((1, 20), (2, 19), (3, 21), (4, 21), (5, 21), (6, 22),
(7, 23), (8, 23), (9, 23), (10, 23), (11, 23), (12, 23))
input_month = int(input("Enter birth month: "))
input_day = int(input("Enter birth day: "))
matched_cutoffs = filter(lambda cutoff: cutoff <= (input_month, input_day), sign_cutoff_dates)
sign_index = len(list(matched_cutoffs)) % 12
print(western_zodiac_signs[sign_index])
List Operations
Basic list usage examples:
sample_list = ["first_entry", "second_entry"]
# Add element to end of list
sample_list.append("new_entry")
# Remove specified element
sample_list.remove("new_entry")
Conditional Statements
Python uses if, elif, else for conditional branching:
test_val = "test_string"
if test_val == "test_string":
print("Value matches expected string")
else:
print("Value does not match expected string")
Chinese zodiac calculation:
chinese_zodiac_chars = "RatOxTigerRabbitDragonSnakeHorseGoatMonkeyRoosterDogPig"
birth_year = int(input("Enter your birth year: "))
zodiac_index = birth_year % 12
print(f"Your Chinese zodiac sign is: {chinese_zodiac_chars[zodiac_index*3 : (zodiac_index+1)*3]}")
Loop Statements
For Loops
# Iterate over string characters
for char in chinese_zodiac_chars:
print(char)
# Iterate over numeric range
for num in range(1, 13):
print(num)
# Print zodiac for years 2000 to 2018
for year in range(2000, 2019):
current_zodiac = chinese_zodiac_chars[(year%12)*3 : (year%12 + 1)*3]
print(f"{year} zodiac sign: {current_zodiac}")
While Loops
counter = 5
while True:
print("Loop running")
counter += 1
if counter == 10:
break # Use continue to skip remaining logic in current iteration
Alternative western zodiac calculation with while loop:
western_zodiac_signs = ("Capricorn", "Aquarius", "Pisces", "Aries", "Taurus", "Gemini",
"Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius")
sign_cutoff_dates = ((1, 20), (2, 19), (3, 21), (4, 21), (5, 21), (6, 22),
(7, 23), (8, 23), (9, 23), (10, 23), (11, 23), (12, 23))
input_month = int(input("Enter birth month: "))
input_day = int(input("Enter birth day: "))
index = 0
while sign_cutoff_dates[index] < (input_month, input_day):
if input_month == 12 and input_day > 23:
break
index += 1
print(western_zodiac_signs[index])
Comprehensions
Calculate squares of even numbers from 1 to 10:
List Comprehension
# Traditional loop implementation
square_list = []
for num in range(1, 11):
if num % 2 == 0:
square_list.append(num ** 2)
print(square_list)
# Equivalent list comprehension
square_list_comp = [num**2 for num in range(1, 11) if num % 2 == 0]
print(square_list_comp)
Dictionary Comprehension
# Traditional loop implementation
init_dict = {}
for val in square_list:
init_dict[val] = 0
# Equivalent dictionary comprehension
init_dict_comp = {val:0 for val in square_list}
File Operations
Basic file read/write and pointer manipulation:
file_handler = open("sample.txt", "r")
# Get current file pointer position
print(f"Current pointer position: {file_handler.tell()}")
# Read 1 character from file
first_char = file_handler.read(1)
print(f"Read character: {first_char}")
print(f"Pointer position after read: {file_handler.tell()}")
# Move pointer 5 bytes from start of file (offset 0 = start, 1 = current, 2 = end)
file_handler.seek(5, 0)
print(f"Pointer position after seek: {file_handler.tell()}")
second_char = file_handler.read(1)
print(f"Read character after seek: {second_char}")
file_handler.close()
Simplified file handling with context manager:
with open("sample.txt", "r") as f:
for line in f:
print(line.strip())
Exception Handling
Common Python exception types:
NameError: Accessing undefined variableSyntaxError: Invalid code syntaxIndentationError: Incorrect code indentationKeyError: Accesisng non-existent dictionary keyValueError: Passing invalid value type to a functionAttributeError: Accessing non-existnet object attribute/methodIOError: File read/write failureImportError: Failed to import module/packageIndexError: Sequence index out of boundsUnboundLocalError: Accessing local variable before assignmentTypeError: Operation on incompatible data types
Exception handling example:
try:
file_handler = open("missing_file.txt", "r")
except Exception as e:
print(f"Error occurred: {str(e)}")
finally:
if 'file_handler' in locals() and not file_handler.closed:
file_handler.close()
Custom exception raising:
try:
raise ValueError("Custom error message")
except ValueError as e:
print(f"Caught custom error: {e}")
Functions
Example function to count character occurrences in a text file:
import re
def count_occurrence(search_term, file_path="sanguo.txt", encoding="GB18030"):
with open(file_path, encoding=encoding) as f:
content = f.read().replace("\n", "")
matches = re.findall(search_term, content)
return len(matches)
# Count occurrences for all names in name list
name_count_map = {}
with open("names.txt", "r") as f:
for line in f:
name_entries = line.strip().split("|")
for name in name_entries:
name_count_map[name] = count_occurrence(name)
# Sort names by occurrence count descending
sorted_names = sorted(name_count_map.items(), key=lambda x: x[1], reverse=True)
print(sorted_names[:10])
Generator Functions (yield)
Example of a floating point range generator:
def float_range(start, end, step):
current = start
while current < end:
yield current
current += step
# Iterate over 0 to 1 with 0.01 step
for val in float_range(0, 1, 0.01):
print(val)
Lambda Expressions
Anonymous function usage with filter, map, zip:
# Equivalent to def add(x,y): return x+y
add_func = lambda x, y: x + y
sample_list = [1,2,3,4,5,6,7]
# Filter values greater than 2
filtered_vals = list(filter(lambda x: x > 2, sample_list))
print(filtered_vals) # Output: [3,4,5,6,7]
# Map function to add 1 to each element
mapped_vals = list(map(lambda x: x + 1, sample_list))
print(mapped_vals) # Output: [2,3,4,5,6,7,8]
# Map with two input lists
list_a = [1,2,3]
list_b = [4,5,6]
sum_vals = list(map(lambda x,y: x + y, list_a, list_b))
print(sum_vals) # Output: [5,7,9]
# Zip function to pair elements from multiple sequences
for paired_val in zip((1,2,3), (4,5,6)):
print(paired_val)
# Output:
# (1,4)
# (2,5)
# (3,6)
Closures
Example closure to create linear function generators:
def create_linear_func(slope, intercept):
def calculate_y(x):
return slope * x + intercept
return calculate_y
# Create function y = 2x + 3
line_func = create_linear_func(2, 3)
print(line_func(5)) # Output: 13