Why Python?
Python is common in AI/ML and scripting:
- Readable syntax
- Rich ecosystem
- AI/ML libraries
- Good for automation
Basic Syntax
Variables
name = "Alice"
age = 30
price = 19.99
active = True
nothing = None
print("Hello")
print(f"Name: {name}, Age: {age}")
Comments
# Single line comment
"""
Multi-line
comment/docstring
"""
Data Types
Strings
s = "Hello, World"
s.lower() # "hello, world"
s.upper() # "HELLO, WORLD"
s.split(", ") # ["Hello", "World"]
s.replace("o", "0") # "Hell0, W0rld"
s.startswith("He") # True
len(s) # 12
# F-strings
name = "Alice"
f"Hello, {name}!" # "Hello, Alice!"
Numbers
x = 10
y = 3
x + y # 13
x - y # 7
x * y # 30
x / y # 3.333...
x // y # 3 (integer division)
x % y # 1 (modulo)
x ** y # 1000 (power)
Lists
items = [1, 2, 3, 4, 5]
items[0] # 1
items[-1] # 5
items[1:3] # [2, 3]
items.append(6) # [1, 2, 3, 4, 5, 6]
items.pop() # 6, items = [1, 2, 3, 4, 5]
len(items) # 5
3 in items # True
Dictionaries
user = {
"name": "Alice",
"age": 30
}
user["name"] # "Alice"
user.get("email") # None
user.get("email", "n/a") # "n/a"
user["email"] = "a@b.com"
user.keys() # dict_keys(['name', 'age', 'email'])
user.values() # dict_values(['Alice', 30, 'a@b.com'])
Sets
s = {1, 2, 3}
s.add(4) # {1, 2, 3, 4}
s.remove(1) # {2, 3, 4}
2 in s # True
Tuples
point = (10, 20)
x, y = point # Unpacking
Control Flow
If/Elif/Else
if age < 18:
print("Minor")
elif age < 65:
print("Adult")
else:
print("Senior")
For Loops
for item in items:
print(item)
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for i, item in enumerate(items):
print(f"{i}: {item}")
While Loops
count = 0
while count < 5:
print(count)
count += 1
Comprehensions
# List comprehension
squares = [x**2 for x in range(10)]
# With condition
evens = [x for x in range(10) if x % 2 == 0]
# Dict comprehension
squared = {x: x**2 for x in range(5)}
Functions
Basic Function
def greet(name):
return f"Hello, {name}!"
greet("Alice") # "Hello, Alice!"
Default Arguments
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet("Alice") # "Hello, Alice!"
greet("Alice", "Hi") # "Hi, Alice!"
Args and Kwargs
def func(*args, **kwargs):
print(args) # Tuple of positional args
print(kwargs) # Dict of keyword args
func(1, 2, 3, a=4, b=5)
Lambda
square = lambda x: x ** 2
square(5) # 25
# Often used with map/filter
list(map(lambda x: x*2, [1, 2, 3])) # [2, 4, 6]
Classes
Basic Class
class User:
def __init__(self, name, email):
self.name = name
self.email = email
def greet(self):
return f"Hello, I'm {self.name}"
user = User("Alice", "alice@example.com")
user.greet() # "Hello, I'm Alice"
Inheritance
class Admin(User):
def __init__(self, name, email, level):
super().__init__(name, email)
self.level = level
File Operations
Reading
with open("file.txt", "r") as f:
content = f.read()
# Or line by line
with open("file.txt", "r") as f:
for line in f:
print(line.strip())
Writing
with open("file.txt", "w") as f:
f.write("Hello, World!")
JSON
import json
# Parse
data = json.loads('{"name": "Alice"}')
# Stringify
text = json.dumps({"name": "Alice"})
# File
with open("data.json") as f:
data = json.load(f)
with open("data.json", "w") as f:
json.dump(data, f)
Error Handling
try:
result = risky_operation()
except ValueError as e:
print(f"Value error: {e}")
except Exception as e:
print(f"Error: {e}")
finally:
cleanup()
Common Modules
import os
os.getcwd() # Current directory
os.path.exists("file.txt") # Check existence
os.environ.get("HOME") # Environment variable
import sys
sys.argv # Command line arguments
import datetime
datetime.datetime.now() # Current time
import re
re.match(r"\d+", "123abc") # Regex
import requests # External
response = requests.get("https://api.example.com")
Pythonic Patterns
Truthiness
if items: # Non-empty list is truthy
process(items)
if not name: # Empty string is falsy
name = "default"
Ternary
status = "active" if user.active else "inactive"
Unpacking
first, *rest = [1, 2, 3, 4] # first=1, rest=[2,3,4]
a, b = b, a # Swap
Context Managers
with open("file.txt") as f:
# f is automatically closed after
Conclusion
Python essentials:
- Clean, readable syntax
- Rich built-in types
- Powerful comprehensions
- Simple class model
- Great for scripting and automation
Master these basics for effective Python work.
Next: JavaScript Essentials - JS fundamentals