Data Types and Variables
Python uses indentation to organize code blocks, typically with 4 spaces. Use # for single-line comments. Each line represents a statement, and when a statement ends with a colon (:), the indented statements form a code block. Python is case-sensitive.
Integers
Python can handle arbitrarily large integers, including negative numbers, written as in mathematics. For hexadecimal representation, use the 0x prefix followed by 0-9 and a-f, such as 0xff00.
Floating-Point Numbers
Floating-point numbers are represented as 3.14 or -9.01. For scientific notation, use e instead of 10, like 1.23e9 for 1.23×10⁹.
Integer and floating-point numbers are stored differently in computers. Integer operations are always precise (including division), while floating-point operations may have rounding errors.
Strings
Strings are text enclosed in single or double quotes.
- If a string contains single quotes, use double quotes to enclose it.
- If it contains double quotes, use single quotes.
- If it contains both, use the escape character \, like 'I\'m "OK"!'
- Use r'' for raw strings that don't escape charactesr, like print(r'\\t\\')
- Use triple quotes for multi-line strings:
print("""line1
line2
line3""")
Boolean Values
Boolean values are either True or False (case-sensitive), commonly used in if conditions.
Boolean operations:
- and: Returns True only if all operands are True
- or: Returns True if at least one operand is True
- not: Inverts the boolean value
None Value
None is a special value in Python representing null or absence of value.
Variables
Python is dynamically typed, so variables don't need prior declaration. Use = for assignment, and variables can be reassigned to different types:
count = 123 # count is an integer
count = "ABC" # count now points to a string
reference = count # reference points to the same data as count
count = "XYZ" # count now points to a different string
print(reference) # prints "ABC"
When assigning count = "ABC", Python:
- Creates the string "ABC" in memory
- Creates a variable named count pointing to "ABC"
- When assigning to reference, it points to the same data
Constants
Constants are conventionally written in uppercase, like PI = 3.14. Python doesn't enforce constancy, so they're technically variables.
Division in Python
- / always returns a float, even for integer division: 9 / 3 = 3.0
- // returns only the integer part: 10 // 3 = 3
- % returns the remainder: 10 % 3 = 1
Strings and Encoding
Character Encoding
- ASCII: Early encoding using 8 bits for English characters, numbers, and symbols
- Unicode: Universal encoding using 16 bits, solving multilingual issues but inefficient for English text
- UTF-8: Variable-length Unicode encoding, using 1-6 bytes per character (1 for ASCII, 3 for Chinese, 4-6 for rare characters)
Encoding Usage
- Use Unicode in memory
- Convert to UTF-8 for storage or transmission
Python Strings
Python 3 strings are Unicode by default. Use ord() to get character code, chr() to convert code to character:
print(ord('A')) # 65
print(ord('中')) # 20013
print(chr(66)) # 'B'
print(chr(25991)) # '米'
String Encoding Conversion
Strings are str type (Unicode). For storage/transmission, convert to bytes:
x = b'ABC' # bytes literal
encode() - str to bytes
'ABC'.encode('ascii') # b'ABC'
'中文'.encode('utf-8') # b'\xe4\xb8\xad\xe6\x96\x87'
decode() - bytes to str
b'ABC'.decode('ascii') # 'ABC'
b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8') # '中文'
len()
For str: counts characters. For bytes: counts bytes.
print(len('ABC')) # 3
print(len('中文')) # 2
print(len(b'ABC')) # 3
print(len(b'\xe4\xb8\xad\xe6\x96\x87')) # 6
String Formatting
% formatting
Use % with format specifiers:
print('Hello, %s' % 'world')
print('Hi, %s, you have $%d.' % ('Michael', 1000000))
print('%2d-%02d' % (3, 1))
print('%.2f' % 3.1415926)
print('Age: %s. Gender: %s' % (25, True))
print('growth rate: %d %%' % 7)
format() method
Alternative formatting method:
print('Hello, {0}, your score is {1:.1f}%'.format('小明', 17.125))
Lists and Tuples
Lists
Mutable ordered collections:
students = ['Alice', 'Bob', 'Charlie']
print(len(students)) # 3
List Operations
- Indexing: students[0] (first), students[-1] (last)
- Append: students.append('David')
- Insert: students.insert(1, 'Eve')
- Pop: students.pop() (removes last), students.pop(1) (removes at index)
- Replace: students[1] = 'Frank'
Multidimensional Lists
matrix = ['python', 'java', ['asp', 'php'], 'scheme']
print(matrix[2][1]) # 'php'
Empty List
empty = []
print(len(empty)) # 0
Tuples
Immutable ordered collections. Single-element tuples need a trailing comma:
t = (1,) # tuple
t = (1) # integer
Special Case
Tuples can contain mutable objects like lists:
t = ('a', 'b', ['A', 'B'])
t[2][0] = 'X'
t[2][1] = 'Y'
print(t) # ('a', 'b', ['X', 'Y'])
Dictionaries and Sets
Dictionaries
Key-value mappings with fast lookups:
scores = {'Alice': 95, 'Bob': 75, 'Charlie': 85}
print(scores['Alice']) # 95
scores['David'] = 67 # add new entry
Dictionary Operations
- Check existence: 'Eve' in scores (False), scores.get('Eve') (None)
- Get with default: scores.get('Eve', -1) (-1)
- Remove: scores.pop('Bob') (75)
Dictionary Characteristics
- Fast lookups regardless of size
- Memory intensive
- Keys must be immutable (strings, numbers, tuples)
Sets
Unordered collections of unique elements:
unique = set([1, 2, 3, 2, 3])
print(unique) # {1, 2, 3}
Set Operations
- Add: unique.add(4)
- Remove: unique.remove(4)
- Intersection: {1, 2, 3} & {2, 3, 4} = {2, 3}
- Union: {1, 2, 3} | {2, 3, 4} = {1, 2, 3, 4}
Immutable Objects
Integers and strings are immutable. Methods return new objects:
s = 'abc'
t = s.replace('a', 'A')
print(s) # 'abc'
print(t) # 'Abc'
Conditional Statements
if Structure
age = 20
if age >= 6:
print('teenager')
elif age >= 18:
print('adult')
else:
print('kid')
Conditional Shorthand
if value:
print('True')
Truthy values: non-zero numbers, non-empty strings, non-empty lists.
Input Handling
birth_year = input('Birth year: ')
year = int(birth_year)
if year < 2000:
print('Born before 2000')
else:
print('Born after 2000')
Loop Statements
for Loops
Iterate over sequences:
names = ['Alice', 'Bob', 'Charlie']
for name in names:
print(name)
Using range():
total = 0
for i in range(101):
total += i
print(total)
while Loops
Repeat while condition is true:
total = 0
n = 99
while n > 0:
total += n
n -= 2
print(total)
break and continue
break: Exit loop prematurely
n = 1
while n <= 100:
if n > 10:
break
print(n)
n += 1
conitnue: Skip current iteration
n = 0
while n < 10:
n += 1
if n % 2 == 0:
continue
print(n)