Variables and Basic Data Types
Variables are labels assigned to values, serving as references to specific data.
Variable Naming Conventions
- Consist of letters, numbers, and underscores
- Cannot start with a number
- Case-sensitive
- Avoid Python keywords and function names
- Use descriptive, concise names
- Prefer lowercase lettters (avoid 'l' and 'O' due to visual ambiguity)
Strings
Strings are sequences of characters anclosed in single or double quotes.
String Case Modification
name = "ada lovelace"
print(name.title()) # Ada Lovelace
print(name.upper()) # ADA LOVELACE
print(name.lower()) # ada lovelace
String Interpolation
Python 3.6+ f-strings:
first = 'ada'
last = 'lovelace'
full = f'{first} {last}'
print(full) # ada lovelace
Pre-3.6 format method:
full = '{} {}'.format(first, last)
String Operations
# Concatenation
combined = first + ' ' + last
# Whitespace removal
language = ' python '
print(language.lstrip()) # 'python '
print(language.rstrip()) # ' python'
print(language.strip()) # 'python'
# String replacement
message = "I really like dogs. My dog names Jack."
message = message.replace('dog', 'cat')
print(message) # I really like cats. My cat names Jack.
# String splitting
words = "hello world python".split()
print(words) # ['hello', 'world', 'python']
# Character counting
text = 'programming'
print(text.count('m')) # 2
Numbers
# Basic operations
result = 3 ** 3 # 27 (exponentiation)
quotient = 10 // 3 # 3 (floor division)
# Large number formatting
universe_age = 14_000_000_000
# Type conversion
age = 23
message = "Happy " + str(age) + "rd Birthday!"
Multiple Assignment
x, y, z = 0, 0, 0
Constants
While Python lacks built-in constants, convention uses uppercase for constant-like variables:
MAX_CONNECTIONS = 5000
Lists
Lists are ordered collections enclosed in square brackets.
List Operations
# Creation and access
vehicles = ['car', 'bike', 'bus']
print(vehicles[0]) # car
print(vehicles[-1]) # bus
# Adding elements
vehicles.append('train')
vehicles.insert(1, 'plane')
# Removing elements
del vehicles[0]
removed = vehicles.pop()
vehicles.remove('bike')
# List organization
numbers = [3, 1, 4, 2]
numbers.sort()
numbers.reverse()
print(len(numbers)) # 4
List Slicing and Copying
items = ['a', 'b', 'c', 'd', 'e']
print(items[1:4]) # ['b', 'c', 'd']
copy_items = items[:] # Creates a copy
List Comprehensions
squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
Tuples
Immutable sequences enclosed in parentheses:
dimensions = (200, 50)
# dimensions[0] = 250 # Error - tuples are immutable
Control Structures
If Statements
numbers = [1, 2, 3, 4]
for num in numbers:
if num % 2 == 0:
print(f'{num} is even')
else:
print(f'{num} is odd')
While Loops
count = 5
while count > 0:
print(count)
count -= 1
Dictionaries
Key-value pair collections enclosed in curly braces.
Dictionary Operations
# Creation and access
student = {'name': 'Alice', 'age': 20, 'grade': 'A'}
print(student['name']) # Alice
# Adding and modifying
student['major'] = 'Computer Science'
student['age'] = 21
# Removing
removed_grade = student.pop('grade')
Dictionary Iteration
for key, value in student.items():
print(f'{key}: {value}')
for key in student.keys():
print(key)
for value in student.values():
print(value)
Functions
Function Definition
def greet_person(name):
"""Display a greeting message"""
return f'Hello, {name}!'
print(greet_person('Bob')) # Hello, Bob!
Function Parameters
# Default parameters
def describe_pet(name, animal='dog'):
return f'I have a {animal} named {name}'
# Variable arguments
def make_sandwich(*ingredients):
return f'Sandwich with: {ingredients}'
# Keyword arguments
def build_profile(**info):
return info
Classes
Class Definition
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
return f'{self.name} says woof!'
my_dog = Dog('Rex', 'German Shepherd')
print(my_dog.bark()) # Rex says woof!
Inheritance
class Puppy(Dog):
def __init__(self, name, breed, age):
super().__init__(name, breed)
self.age = age
File Operations
Reading Files
with open('data.txt') as file:
content = file.read()
with open('data.txt') as file:
for line in file:
print(line.strip())
Writting Files
with open('output.txt', 'w') as file:
file.write('Hello, World!\n')
Error Handling
try:
result = 10 / 0
except ZeroDivisionError:
print('Cannot divide by zero')
else:
print('Division successful')
Testing
import unittest
def add_numbers(a, b):
return a + b
class TestMath(unittest.TestCase):
def test_addition(self):
self.assertEqual(add_numbers(2, 3), 5)
if __name__ == '__main__':
unittest.main()