Python Programming Essentials: Syntax, Data Structures, and Objects
Naming Conventions
- Identifiers cannot start with a digit.
- Python is case-sensitive.
- Reserved keywords cannot be used as identifiers.
Comments
Single-line
Use the hash symbol #:
# This is a single line comment
x = 10
Multi-line
Use triple double quotes """:
"""
This is a
multi-line comment
"""
Docstrings
In side a function definition, typing three quotes and pressing Enter automatically generates a docstirng template.
def calculate_sum():
"""Describe the function here."""
pass
Operators
Standard arithmetic includes addition +, subtraction -, multiplication *, division /, floor division //, modulo %, and exponentiation **. Assignment uses =, and compound operators include +=, -=, *=, /=, %=, **=, and //=.
Division Behavior
Standard division / results in a float, even if the numbers divide evenly. Use floor division // to retain integer types.
x = 10
y = 3
result_float = x / y
print(result_float, type(result_float)) # 3.333... <class 'float'>
result_int = x // y
print(result_int, type(result_int)) # 3 <class 'int'>
Exponentiation
base = 10
exp = 2
power_result = base ** exp
print(power_result) # 100
Modules
Modules are files containing Python code (functions, classes, variables). They help organize code for reusability, similar to headers in C.
Import Syntax
[from module_name] import [module | class | var | func | *] [as alias]
Common Patterns
import math
from os import path
from sys import *
import numpy as np
from pandas import DataFrame as DF
Usage Exmaples
# Import entire module
import time
time.sleep(5)
# Import all (not recommended for large scopes)
from time import *
sleep(5)
# Alias for module
import time as t
t.sleep(5)
# Alias for specific function
from time import sleep as pause
pause(5)
Custom Modules
You can import specific functions directly without instantiating a class.
from my_module import specific_function
Caution:
- When importing, Python executes the top-level code in the imported module. To prevent this, wrap executable code in:
def helper():
print("Running helper")
if __name__ == "__main__":
helper()
- If two modules have functions with the same name, the last imported one takes precedence.
from mod_a import func
from mod_b import func # func now refers to mod_b's version
The __main__ Guard
This ensures code runs only when the file is executed directly, not when imported.
def greet():
print("Hello")
if __name__ == "__main__":
greet()
The __all__ Variable
Limits what is imported when using from module import *.
__all__ = ["public_func"]
def public_func():
print("Accessible")
def _private_func():
print("Hidden from * import")
Packages
A package is a directory containing an __init__.py file and modules, similar to a Maven structure in Java.
Installation
Use pip to install third-party packages:
pip install requests
To use a Chinese mirror for speed:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests
Usage
import package_name.module_name
package_name.module_name.function()
Input and Output
Printing
print("Hello World")
val = 50
txt = "Sample"
pi = 3.14
print(val, txt, pi)
User Input
The input() function always returns a string.
user = input("Enter username: \n")
role = input("Enter role: \n")
print(f"Welcome {user}, you are a {role}")
Data Types
Python is dynamically typed; the variable type is determined by the assigned value.
Numbers
- int:
10,-5 - float:
3.14 - complex:
1+2j
Precision Formatting
Use format specifiers to control width (m) and precision (n).
price = 54.155
# Width 7, Precision 2
print("Price: %7.2f" % price) # " 54.16"
Strings
Strings are immutable sequences of characters. No separate char type exists.
Definition:
s1 = 'Hello'
s2 = "World"
s3 = """Multi-line string"""
Concatenation:
first = "Data"
last = "Base"
print(first + last + "!")
Formatting:
# Old style
name = "Bob"
print("Hi %s" % name)
# Format method
age = 30
msg = "I am {} years old".format(age)
# F-strings
msg = f"I am {age} years old"
Comparison:
Strings compare lexicographically based on ASCII values (e.g., 'abc' < 'b').
Booleans and None
is_valid = True
empty = None
print(type(empty)) # <class 'NoneType'>
Data Containers
List
Ordered, mutable, allows duplicates.
my_list = [1, 2, 3, "four"]
matrix = [[1, 2], [3, 4]]
# Indexing
print(my_list[0]) # 1
print(my_list[-1]) # "four"
print(matrix[0][1]) # 2
# Iteration
for item in my_list:
print(item)
idx = 0
while idx < len(my_list):
print(my_list[idx])
idx += 1
Tuple
Ordered, immutable, allows duplicates.
my_tuple = (1, 2, 3)
# Single element requires comma
single = (5,)
Set
Unordered, mutable, no duplicates.
my_set = {1, 2, 3, 3} # {1, 2, 3}
# Iteration (No indexing)
for val in my_set:
print(val)
Dictionary
Unordered (prior to 3.7) key-value pairs, keys must be unique.
my_dict = {"id": 101, "name": "Alice"}
# Nested
employees = {
"emp1": {"dept": "HR"},
"emp2": {"dept": "IT"}
}
# Iteration
for key in my_dict:
print(my_dict[key])
Slicing
Extract subsequences using [start:end:step].
data = "abcdef"
print(data[1:4]) # bcd
print(data[::2]) # ace
print(data[::-1]) # fedcba
JSON Handling
import json
# List to JSON
users = [{"name": "Zhang"}]
json_str = json.dumps(users, ensure_ascii=False)
# Dict to JSON
details = {"name": "Jay"}
json_str = json.dumps(details, ensure_ascii=False)
Control Flow
Conditionals
age = 20
if age < 18:
print("Minor")
elif age < 65:
print("Adult")
else:
print("Senior")
# Membership
if "a" in "banana":
print("Found")
Loops
# For loop
counter = 0
for char in "hello":
if char == "l":
counter += 1
print(counter)
# While loop
x = 0
while x < 5:
x += 1
# Break and Continue
for i in range(10):
if i == 3:
continue
if i == 8:
break
print(i)
Functions
Definition
def greet_user(msg):
print(msg)
return None
Parameters
- Positional:
func(1, "A") - Keyword:
func(name="A", id=1) - Default:
def func(id, name="Default") - Arbitrary:
*args(tuple):def func(*args)**kwargs(dict):def func(**kwargs)
Lambda (Anonymous)
square = lambda x: x * x
print(square(5))
# In higher-order functions
def apply_op(op, a, b):
return op(a, b)
result = apply_op(lambda x, y: x * y, 3, 4)
Object-Oriented Programming
Class Definition
class Car:
# Class attribute
wheels = 4
# Initializer (Constructor)
def __init__(self, brand, speed):
self.brand = brand
self.speed = speed
# Method
def display(self):
print(f"{self.brand} at {self.speed}km/h")
Usage
# Instance creation
my_car = Car("Toyota", 120)
# Accessing attributes and methods
my_car.speed = 140
my_car.display()
# Global variable inside function
def update_val():
global global_var
global_var = 100
Magic Methods
__init__: Constructor.__str__: String representation for printing.
class Book:
def __init__(self, title):
self.title = title
def __str__(self):
return f"Book: {self.title}"