| name | python-basics |
| description | Python fundamentals reference covering data types, operators, control flow, data structures (lists, tuples, dicts, sets), classes, functions, generators, regex, and itertools. Use this skill whenever the user asks about Python syntax, basic operations, data structures, string manipulation, file I/O, error handling, or any Python programming question. Trigger on queries about Python lists, dictionaries, tuples, sets, classes, functions, lambda, map, filter, zip, decorators, generators, regular expressions, or any Python learning/teaching request. |
Python Basics Reference
A comprehensive guide to Python fundamentals. Use this as your go-to reference for Python syntax, data structures, and common operations.
Core Operations
Arithmetic & Comparison
- Power:
3**2 (not 3^2)
- Division:
2/3 returns 0 (int division in Python 2), use 2.0/3.0 for decimals
- Comparisons:
>=, <=, ==, !=
- Logic:
and, or, not
Type Conversions
float(a)
int(a)
str(d)
ord("A")
chr(65)
hex(100)
hex(100)[2:]
isinstance(1, int)
String Operations
"a b".split(" ")
" ".join(['a', 'b'])
"abcdef".startswith("ab")
"abc\n".strip()
"apbc".replace("p", "")
"a".upper()
"A".lower()
"abc".capitalize()
String Indexing & Slicing
'abc'[0]
'abc'[-1]
'abc'[1:3]
"qwertyuiop"[:-1]
String & List Concatenation
3 * 'a'
'a' + 'b'
'a' + str(3)
[1,2,3] + [4,5]
Data Structures
Lists
d = []
a = [1, 2, 3]
b = [4, 5]
a + b
b.append(6)
tuple(a)
sum([1, 2, 3])
sorted([1, 43, 5, 3, 21, 4])
Tuples
t1 = (1, '2', 'three')
t2 = (5, 6)
t3 = t1 + t2
(4,)
d = ()
d += (4,)
list(t2)
Key difference: Tuples have structure (position gives meaning), lists have order.
Dictionaries
d = {}
monthNumbers = {1: 'Jan', 2: 'Feb', 'Feb': 2}
monthNumbers[1]
monthNumbers['Feb']
list(monthNumbers)
monthNumbers.values()
monthNumbers.keys()
monthNumbers.update({'9': 9})
mN = monthNumbers.copy()
monthNumbers.get('key', 0)
Sets
myset = set(['a', 'b'])
myset.add('c')
myset.add('a')
myset.update([1, 2, 3])
myset.discard(10)
myset.remove(10)
myset.union(myset2)
myset.intersection(myset2)
myset.difference(myset2)
myset.symmetric_difference(myset2)
myset.pop()
myset.intersection_update(myset2)
myset.difference_update(myset2)
Control Flow
Conditionals
if a:
elif b:
else:
Loops
while(a):
for i in range(0, 100):
for letter in "hola":
Comments
"""
Several lines comment
Another one
"""
Functions & Advanced Concepts
Lambda Functions
(lambda x, y: x + y)(5, 3)
sorted(range(-5, 6), key=lambda x: x**2)
filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])
def make_adder(n):
return lambda x: x + n
plus3 = make_adder(3)
plus3(4)
class Car:
crash = lambda self: print('Boom!')
my_car = Car()
my_car.crash()
Map, Filter, Zip
m = map(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])
for f, b in zip(foo, bar):
print(f, b)
m = filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])
List Comprehensions
mult1 = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9] if x % 3 == 0]
squared = [x**2 for x in range(10)]
Classes
Basic Class
class Person:
def __init__(self, name):
self.name = name
self.lastName = name.split(' ')[-1]
self.birthday = None
def __lt__(self, other):
if self.lastName == other.lastName:
return self.name < other.name
return self.lastName < other.lastName
def setBirthday(self, month, day, year):
from datetime import date
self.birthday = date(year, month, day)
def getAge(self):
from datetime import date
return (date.today() - self.birthday).days
Inheritance
class MITPerson(Person):
nextIdNum = 0
def __init__(self, name):
Person.__init__(self, name)
self.idNum = MITPerson.nextIdNum
MITPerson.nextIdNum += 1
def __lt__(self, other):
return self.idNum < other.idNum
Error Handling
Try-Except
def divide(x, y):
try:
result = x / y
except ZeroDivisionError as e:
print("division by zero!" + str(e))
except TypeError:
divide(int(x), int(y))
else:
print("result is", result)
finally:
print("executing finally clause in any case")
Assertions
def avg(grades, weights):
assert len(grades) != 0, 'no grades data'
assert len(grades) == len(weights), 'wrong number of grades'
Generators
def myGen(n):
yield n
yield n + 1
g = myGen(6)
next(g)
next(g)
next(g)
Why use generators: They save memory by yielding values one at a time instead of creating a full list.
Regular Expressions
import re
re.search(r"\w", "hola").group()
re.findall(r"\w", "hola")
re.findall(r"\w+(la)", "hola caracola")
Special Characters
| Pattern | Meaning |
|---|
. | Any character |
\w | [a-zA-Z0-9_] |
\d | Digit |
\s | Whitespace ( \n\r\t\f) |
\S | Non-whitespace |
^ | Start of string |
$ | End of string |
+ | One or more |
* | Zero or more |
? | Zero or one |
Options
re.search(pat, str, re.IGNORECASE)
re.search(pat, str, re.DOTALL)
re.search(pat, str, re.MULTILINE)
Non-greedy Matching
re.findall(r"<.*>", "<b>foo</b>and<i>so on</i>")
re.findall(r"<.*?>", "<b>foo</b>and<i>so on</i>")
Itertools
from itertools import product, permutations, combinations, combinations_with_replacement
list(product([1, 2, 3], [3, 4]))
list(product([1, 2, 3], repeat=2))
list(permutations(['1', '2', '3']))
list(permutations('123', 2))
list(combinations('123', 2))
list(combinations_with_replacement('1133', 2))
Decorators
from functools import wraps
import time
def timeme(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Let's call our decorated function")
start = time.time()
result = func(*args, **kwargs)
print(f'Execution time: {time.time() - start:.6f} seconds')
return result
return wrapper
@timeme
def decorated_func():
print("Decorated func!")
decorated_func()
Quick Reference
Python 2 vs 3
range() in Python 3 = xrange() in Python 2 (generator, not list)
print is a function in Python 3: print("hello")
- Division:
2/3 = 0 in Python 2, 0.666... in Python 3
Getting Help
dir(str)
help(str)
help(function_name)
Common Patterns
if key in my_dict:
value = my_dict[key]
value = my_dict.get(key, default_value)
for i, item in enumerate(items):
print(i, item)
for a, b in zip(list1, list2):
print(a, b)
sum([x**2 for x in range(10)])
When to Use This Skill
Use this skill when:
- Learning Python basics or reviewing syntax
- Need quick reference for data structures
- Writing Python code and need to recall operations
- Debugging Python code
- Teaching Python to others
- Converting between data types
- Working with strings, lists, dicts, sets, or tuples
- Need help with regex patterns
- Understanding generators, decorators, or lambda functions