Essential Python Concepts and Syntax for Beginners
Code Organization
Store reusable Python modules in a dedicated utils directory.
Fundamental Operations
Strings, lists, and tuples support membership testing using in and not in operators.
Multi-line statements can be joined using backslash (\) continuation.
Multiple statements on a single line are separated by semicolons (;).
The print() function automatical adds a newline character. This behavior can be customized:
# Suppress newline
print(x, end="")
# Add space instead of newline
print(x, end=" ")
Data Types
Numeric Types
Boolean values are subclasses of integers where True equals 1 and False equals 0:
>>> True == 1
True
>>> False == 0
True
>>> True + 1
2
>>> 2 / 4 # Returns float
0.5
>>> 2 // 4 # Integer division
0
>>> 2 ** 5 # Exponentiation
32
Format decimal precision:
print("{:.3f}".format(result))
Convert binary string to decimal:
binary_str = "1111"
print(int(binary_str, 2)) # Outputs 15
String Operations
Triple quotes (''' or """) create multi-line strings.
Escape sequences use backslash (\).
Concatenate with + and repeat with * operators.
Strings support dual indexing: left-to-right starting at 0, right-to-left starting at -1.
Strings are immutable - assignment to index positions raises errors.
String slicing operations:
print(text[2:5]) # Characters from index 2 to 4
print(text[2:]) # From index 2 to end
print(text[1:5:2]) # Every second character from index 1 to 4
Boolean Logic
Truthy values include non-zero numbers and non-empty containers. Falsy values are 0, empty strings, empty lists, and empty tuples.
Lists
Mutable sequences enclosed in square brackets [ ] with comma-separated elements.
Support concatenation (+) and repetition (*) operations.
Elements can be modified and may have different data types.
Tuples
Immutable sequences in parentheses ( ) with comma-separated elements.
Can contain mutable objects like lists.
Special syntax for empty or single-element tuples:
tuple_empty = ()
tuple_single = (20,)
Strings, lists, and tuples are all sequence types.
Sets
Unordered mutable clolections storing unique elements.
Defined with curly braces { } or set() constructor.
Empty sets require set() since {} creates dictionaries.
websites = {'Google', 'Taobao', 'Runoob', 'Facebook', 'Zhihu', 'Baidu'}
print(websites)
# Membership test
if 'Runoob' in websites:
print('Found')
# Set operations
first_set = set('abracadabra')
second_set = set('alacazam')
print(first_set - second_set) # Difference
print(first_set | second_set) # Union
print(first_set & second_set) # Intersection
print(first_set ^ second_set) # Symmetric difference
Dictionaries
Unordered key-value mappings enclosed in { }.
Access elements via keys rather than numeric indices.
Iterate over key-value pairs:
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for key, value in knights.items():
print(key, value)
Control Structures
Input/Output Formatting
Format strings using f-strings:
f'{timer.stop():.5f} sec'
# Output: 0.02684 sec
Visualization
Create scatter plots:
d2l.plt.scatter(features[:, 1].detach().numpy(), labels.detach().numpy(), 1)
Iteration Patterns
Parallel iteration with zip():
for x, y in zip(list_a, list_b):
print(x, y)
Conditional Statemants
Structure: if – elif – else
Loop Constructs
While loops:
while counter <= n:
total += counter
counter += 1
# With else clause
while condition:
statements
else:
final_statements
For loops:
for item in iterable:
statements
else:
final_statements
# Examples
for site in ["Baidu", "Google", "Runoob"]:
print(site)
for char in 'runoob':
print(char)
for num in range(1, 6):
print(num)
Control flow keywords: break, continue, pass
The pass statement maintains syntactic structure without performing actions:
for letter in 'Runoob':
if letter == 'o':
pass
print('Current letter:', letter)
Utilities
Iterators and Generators
Generator functions use yield to produce values incrementally:
def countdown(start):
while start > 0:
yield start
start -= 1
counter = countdown(5)
print(next(counter)) # 5
print(next(counter)) # 4
for value in counter:
print(value) # 3, 2, 1
Lambda Functions
Apply transformations to sequences:
result = list(map(lambda x: x**2, [1, 2, 3, 4, 5]))
print(result) # [1, 4, 9, 16, 25]
Reduce sequences to single values:
from functools import reduce
product = reduce(lambda x, y: x * y, [1, 2, 3, 4, 5])
print(product) # 120