# Basic output statement
print("hello world")
Python code executes line by line from top to bottom. Execution stops if an error occurs.
Constants
Constants represent immutable values that remain unchanged during program execution. By convention, they are written in uppercase letters.
# Examples of constants
A = 10
PI = 3.14159
COMPANY_NAME = "TechCorp"
Variables
Variables store data that may change during program execution. Variable names can contain letters, numbers, and underscores but cannot start with a number. Assignment uses the equals sign (=).
variable_name = value
Python keywords cannot be used as variable names. The keyword module provides the complete list:
import keyword
print(keyword.kwlist)
# Variable assignment and reassignment
price = 5.8
print(price)
price = 3.9
print(price)
Comments
Comments document code for better readability:
- Single-line: Starts with #
- Multi-line: Enclosed in triple quotes (single or double)
# Single line comment
'''
Multi-line
comment
'''
"""
Another multi-line
comment
"""
Comment guidelines:
- Don't comment obvious code
- Document complex operations
- Add inline comments for unclear code
- Focus on explaining intent, not describing code
Data Types
Python has six standard data types:
- Number
- String
- List
- Tuple
- Set
- Dictionary
Immutable types: Number, String, Tuple Mutable types: List, Dictionary, Set
Numbers
Python numeric types are immutable.
Integer (int)
Whole numbers without decimal points:
# Examples: 1, -258, 36900
Float
Numbers with decimal components:
# Examples: 3.25, 0.35
Complex
Numbers with real and imaginary parts
Arithmetic Operators
| Operator | Description |
|---|---|
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| / | Division |
| % | Modulus |
| // | Floor division |
| ** | Exponentiation |
Assignment Operators
| Operator | Example | Equivalent |
|---|---|---|
| = | a = 5 | a = 5 |
| += | a += 3 | a = a + 3 |
| -= | a -= 2 | a = a - 2 |
| *= | a *= 4 | a = a * 4 |
| /= | a /= 2 | a = a / 2 |
| //= | a //= 3 | a = a // 3 |
| %= | a %= 5 | a = a % 5 |
| **= | a **= 2 | a = a ** 2 |
Logical Operators
| Operator | Description | Example |
|---|---|---|
| and | Both conditions True | True and False → False |
| or | Either condition True | True or False → True |
| not | Negates condition | not False → True |
Membership Operators
| Operator | Description | Example |
|---|---|---|
| in | Element in sequence | "python" in ["java", "python"] → True |
| not in | Element not in sequence | "node" not in ["java", "python"] → True |
Operator Precedence
Highest to lowest:
- Exponentiation (**)
- Multiplication, division, modulus, floor division (*, /, %, //)
- Addition, subtraction (+, -)
Type Conversion
# Float to integer conversion (precision loss)
value = 2.3
print(int(value)) # Output: 2
# Decimal to binary
print(bin(5)) # Output: 0b101
# Binary to decimal
print(int('110', 2)) # Output: 6
Boolean Type
True and False are boolean values. True equals 1, False equals 0 in numeric context.
# Boolean operations
result = (a and b or c) and d or e
Strings
String Formats
Strings can be enclosed in single or double quotes:
'content'
"content"
Escape Sequences
Common escape sequences:
- \: Backslash
- \n: Newline
- \t: Tab
# Raw strings ignore escape sequences
print(r"hello \n world") # Output: hello \n world
String Concatenation
print("hello" + "world") # Output: helloworld
String Formatting
# Using format() method
message = 'My name is {}, I like {}'.format('John', 'coding')
print(message)
# Using % formatting
message = "My name is %s, I like %s" % ("John", "coding")
print(message)
String Methods
Transformation Methods
- capitalize(): First character uppercase
- center(): Center string with padding
- encode(): Encode to specified format
- join(): Join sequence elements
- len(): Return string length
- lower(): Convert to lowercase
- upper(): Convert to uppercase
- strip(): Remove leading/trailing whitespace
- split(): Split by delimiter
- replace(): Replace substring
Search Methods
- count(): Count substring occurrences
- find(): Find substring position
- index(): Find substring (raises error if not found)
Validation Methods
- startswith(): Check prefix
- endswith(): Check suffix
- isalnum(): Alphanumeric check
- isalpha(): Alphabetic check
- isdigit(): Digit check
- isnumeric(): Numeric check
Lists
Lists store ordered collections of elements. Elements are comma-separated within square brackets.
# List definition
items = [1, "fireworks"]
print(items) # Output: [1, 'fireworks']
Adding Elements
# Create empty list
stock_list = []
stock_list.append("storm approaching")
stock_list.append(999)
print(stock_list) # Output: ['storm approaching', 999]
Indexing
List elements are accessed by zero-based index.
Accessing Elements
stocks = ['Moutai', 'Yili', 'Tongrentang', 'Haitian', 'YunnanBaiyao']
print(stocks[0]) # Output: Moutai
print(stocks[1:4]) # Output: ['Yili', 'Tongrentang', 'Haitian']
Updating Elements
stocks[1] = "fireworks"
print(stocks[1]) # Output: fireworks
Removing Elements
# Using del
stocks = ['Moutai', 'Yili', 'Pianzaihuang', 'Tongrentang']
del stocks[0]
print(stocks) # Output: ['Yili', 'Pianzaihuang', 'Tongrentang']
# Using pop()
stocks.pop(1)
print(stocks) # Output: ['Yili', 'Tongrentang']
List Operations
# Concatenation
list1 = ['Moutai', 'Pianzaihuang']
list2 = ['Yili', 'Tongrentang']
combined = list1 + list2
print(combined) # Output: ['Moutai', 'Pianzaihuang', 'Yili', 'Tongrentang']
# Nesting
nested = [list1, list2]
print(nested) # Output: [['Moutai', 'Pianzaihuang'], ['Yili', 'Tongrentang']]
List Methods
- len(): Element count
- max(): Maximum value
- min(): Minimum value
- count(): Element frequency
- insert(): Insert at position
- clear(): Remove all elements
- sort(): Sort elements
- extend(): Append multiple elements
- pop(): Remove by position
- remove(): Remove by value
- reverse(): Reverse order
Tuples
Tuples are immutable sequences enclosed in parentheses.
Tuple Definition
# Tuple creation
companies = ('Pianzaihuang', 'Tongrentang')
print(companies) # Output: ('Pianzaihuang', 'Tongrentang')
print(companies[1]) # Output: Tongrentang
Tuple Extension
# Concatenation creates new tuple
additional = ('Wuliangye', 'Yili')
extended = companies + additional
print(extended) # Output: ('Pianzaihuang', 'Tongrentang', 'Wuliangye', 'Yili')
Tuple Deletion
# Delete entire tuple
del extended
Tuple Methods
- len(): Element count
- max(): Maximum value
- min(): Minimum value
- count(): Value frequency
- index(): Value position
Sets
Sets store unordered collections of unique elements. Created with {} or set().
Set Creation
# Set definition
company_set = {'Yili', 'Moutai'}
print(company_set)
# From string
chars = set("Pianzaihuang")
print(chars)
# Membership test
print('Yili' in company_set) # Output: True
Set Methods
- add(): Add element
- update(): Add multiple elements
- remove(): Remove element (error if missing)
- pop(): Remove random element
- discard(): Remove element (no error if missing)
- clear(): Remove all elements
- intersection(): Set intersection
- difference(): Set difference
- union(): Set union
Dictionaries
Dictionaries store key-value pairs. Keys must be immutable and unique.
Dictionary Creation
# Dictionary definition
prices = {'Moutai': 2000, 'Pianzaihuang': 400}
print(prices) # Output: {'Moutai': 2000, 'Pianzaihuang': 400}
Adding Values
prices['Yili'] = 35
print(prices) # Output: {'Moutai': 2000, 'Pianzaihuang': 400, 'Yili': 35}
Modifying Values
prices['Moutai'] = 2500
print(prices['Moutai']) # Output: 2500
Removing Entries
# Remove specific key-value pair
del prices['Yili']
print(prices) # Output: {'Moutai': 2500, 'Pianzaihuang': 400}
# Delete entire dictionary
del prices
Dictionary Methods
- len(): Key count
- clear(): Remove all items
- pop(): Remove by key
- popitem(): Remove last item
- get(): Retrieve value by key
- setdefault(): Get value with default
- copy(): Create copy
- keys(): All keys
- values(): All values