Basics
Functions
Basic Function Definition
def add_numbers(x, y):
return x + y
# Usage
result = add_numbers(1, 2)
print(result) # Output: 3
Function with Optional Parameter
def add_numbers(x, y, z=None):
if z is None:
return x + y
else:
return x + y + z
# Usage
print(add_numbers(1, 2)) # Output: 3
print(add_numbers(1, 2, 3)) # Output: 6
Function with Flag Parameter
def add_numbers(x, y, z=None, flag=False):
if flag:
print('Flag is true!')
if z is None:
return x + y
else:
return x + y + z
# Usage
print(add_numbers(1, 2, flag=True)) # Output: Flag is true! 3
Assigning Functions to Variables
def add_numbers(x, y):
return x + y
a = add_numbers
print(a(1, 2)) # Output: 3
Types and Sequences
Basic Types
print(type('This is a string')) # Output: <class 'str'>
print(type(None)) # Output: <class 'NoneType'>
print(type(1)) # Output: <class 'int'>
print(type(1.0)) # Output: <class 'float'>
print(type(add_numbers)) # Output: <class 'function'>
Tuples
Tuples are immutable data structures.
x = (1, 'a', 2, 'b')
print(type(x)) # Output: <class 'tuple'>
Lists
Lists are mutable data structures.
x = [1, 'a', 2, 'b']
print(type(x)) # Output: <class 'list'>
x.append(3.3)
print(x) # Output: [1, 'a', 2, 'b', 3.3]
Looping through Lists
# Using for loop
for item in x:
print(item)
# Using while loop
i = 0
while i != len(x):
print(x[i])
i += 1
List Operations
# Concatenation
print([1, 2] + [3, 4]) # Output: [1, 2, 3, 4]
# Repetition
print([1] * 3) # Output: [1, 1, 1]
# Membership
print(1 in [1, 2, 3]) # Output: True
Strings
String Slicing
x = 'This is a string'
print(x[0]) # Output: T
print(x[0:1]) # Output: T
print(x[0:2]) # Output: Th
print(x[-1]) # Output: g
print(x[-4:-2]) # Output: ri
print(x[:3]) # Output: Thi
print(x[3:]) # Output: s is a string
String Operations
firstname = 'Christopher'
lastname = 'Brooks'
# Concatenation
print(firstname + ' ' + lastname) # Output: Christopher Brooks
# Repetition
print(firstname * 3) # Output: ChristopherChristopherChristopher
# Membership
print('Chris' in firstname) # Output: True
# Splitting
fullname = 'Christopher Arthur Hansen Brooks'
firstname = fullname.split(' ')[0]
lastname = fullname.split(' ')[-1]
print(firstname) # Output: Christopher
print(lastname) # Output: Brooks
String Concatenation with Non-Strings
# This will cause an error
# 'Chris' + 2
# Correct way
print('Chris' + str(2)) # Output: Chris2
String Formatting
sales_record = {
'price': 3.24,
'num_items': 4,
'person': 'Chris'
}
sales_statement = '{} bought {} item(s) at a price of {} each for a total of {}'
print(sales_statement.format(sales_record['person'],
sales_record['num_items'],
sales_record['price'],
sales_record['num_items'] * sales_record['price']))
# Output: Chris bought 4 item(s) at a price of 3.24 each for a total of 12.96
Dictionaries
Basic Dictionary Operations
x = {'Christopher Brooks': 'brooksch@umich.edu', 'Bill Gates': 'billg@microsoft.com'}
print(x['Christopher Brooks']) # Output: brooksch@umich.edu
x['Kevyn Collins-Thompson'] = None
print(x['Kevyn Collins-Thompson']) # Output: None
Iterating over Dictionaries
# Iterating over keys
for name in x:
print(x[name])
# Iterating over values
for email in x.values():
print(email)
# Iterating over items
for name, email in x.items():
print(name)
print(email)
Unpacking Sequences
x = ('Christopher', 'Brooks', 'brooksch@umich.edu')
fname, lname, email = x
print(fname) # Output: Christopher
print(lname) # Output: Brooks
# Ensure number of variables matches the number of values
# This will cause an error
# x = ('Christopher', 'Brooks', 'brooksch@umich.edu', 'Ann Arbor')
# fname, lname, email = x
More on Strings
String Concatenation and Conversion
# This will cause an error
# print('Chris' + 2)
# Correct way
print('Chris' + str(2)) # Output: Chris2
String Formatting
sales_record = {
'price': 3.24,
'num_items': 4,
'person': 'Chris'
}
sales_statement = '{} bought {} item(s) at a price of {} each for a total of {}'
print(sales_statement.format(sales_record['person'],
sales_record['num_items'],
sales_record['price'],
sales_record['num_items'] * sales_record['price']))
# Output: Chris bought 4 item(s) at a price of 3.24 each for a total of 12.96
Reading and Writing CSV Files
import csv
with open('datasets/mpg.csv') as csvfile:
mpg = list(csv.DictReader(csvfile))
print(mpg[:3]) # Output: First three dictionaries in our list
print(len(mpg)) # Output: 234
print(mpg[0].keys()) # Output: dict_keys(['', 'manufacturer', 'model', 'displ', 'year', 'cyl', 'trans', 'drv', 'cty', 'hwy', 'fl', 'class'])
# Average city mpg
avg_cty_mpg = sum(float(d['cty']) for d in mpg) / len(mpg)
print(avg_cty_mpg) # Output: 16.86
# Average highway mpg
avg_hwy_mpg = sum(float(d['hwy']) for d in mpg) / len(mpg)
print(avg_hwy_mpg) # Output: 23.44
# Unique cylinder values
cylinders = set(d['cyl'] for d in mpg)
print(cylinders) # Output: {'4', '5', '6', '8'}
# Average city mpg by cylinder
CtyMpgByCyl = []
for c in cylinders:
summpg = 0
cyltypecount = 0
for d in mpg:
if d['cyl'] == c:
summpg += float(d['cty'])
cyltypecount += 1
CtyMpgByCyl.append((c, summpg / cyltypecount))
CtyMpgByCyl.sort(key=lambda x: x[0])
print(CtyMpgByCyl) # Output: [('4', 21.01), ('5', 20.50), ('6', 16.22), ('8', 12.57)]
# Unique vehicle classes
vehicleclass = set(d['class'] for d in mpg)
print(vehicleclass) # Output: {'2seater', 'compact', 'midsize', 'minivan', 'pickup', 'subcompact', 'suv'}
# Average highway mpg by class
HwyMpgByClass = []
for t in vehicleclass:
summpg = 0
vclasscount = 0
for d in mpg:
if d['class'] == t:
summpg += float(d['hwy'])
vclasscount += 1
HwyMpgByClass.append((t, summpg / vclasscount))
HwyMpgByClass.sort(key=lambda x: x[1])
print(HwyMpgByClass) # Output: [('pickup', 16.88), ('suv', 18.13), ('minivan', 22.36), ('2seater', 24
.80), ('midsize', 27.29), ('subcompact', 28.14), ('compact', 28.30)]
Dates and Times
Current Time and Date
import datetime as dt
import time as tm
# Current time in seconds since the Epoch
print(tm.time()) # Output: e.g., 1712531779.13
# Convert timestamp to datetime
dtnow = dt.datetime.fromtimestamp(tm.time())
print(dtnow) # Output: datetime.datetime(2024, 4, 7, 19, 16, 19, 198895)
# Datetime attributes
print(dtnow.year, dtnow.month, dtnow.day, dtnow.hour, dtnow.minute, dtnow.second) # Output: (2024, 4, 7, 19, 16, 19)
# Time difference
delta = dt.timedelta(days=100)
print(delta) # Output: datetime.timedelta(days=100)
# Current date
today = dt.date.today()
print(today - delta) # Output: date 100 days ago
# Compare dates
print(today > today - delta) # Output: True
Objects and map()
Defining a Class
class Person:
department = 'School of Information' # Class variable
def set_name(self, new_name): # Method
self.name = new_name
def set_location(self, new_location):
self.location = new_location
# Usage
person = Person()
person.set_name('Christopher Brooks')
person.set_location('Ann Arbor, MI, USA')
print('{} lives in {} and works in the department {}'.format(person.name, person.location, person.department))
# Output: Christopher Brooks lives in Ann Arbor, MI, USA and works in the department School of Information
Using map()
store1 = [10.00, 11.00, 12.34, 2.34]
store2 = [9.00, 11.10, 12.34, 2.01]
cheapest = map(min, store1, store2)
# Iterating through map object
for item in cheapest:
print(item) # Output: 9.0, 11.0, 12.34, 2.01
Lambda and List Comprehensions
Lambda Functions
# Lambda function
my_function = lambda a, b, c: a + b
# Usage
print(my_function(1, 2, 3)) # Output: 3
List Comprehensions
# Standard loop
my_list = []
for number in range(0, 1000):
if number % 2 == 0:
my_list.append(number)
print(my_list)
# List comprehension
my_list = [number for number in range(0, 1000) if number % 2 == 0]
print(my_list)
Notebooks
Python Resources
Getting Started with Python
Installing Python
- If Python is installed: Execute the interpreter by running the
python3
command (or justpython
on Windows). - To exit: Use the command
exit()
or pressCtrl-D
. - If Python is not installed: Installation instructions will be provided in an upcoming course section.
Practicing Python Online
For those who want to practice without installing Python, online interpreters and codepads are excellent alternatives. Here are some recommended resources:
- Python.org Shell
- Online GDB Python Interpreter
- Repl.it Python 3
- TutorialsPoint Python 3
- Rextester Python 3
- Trinket.io Python 3
Additional Python Resources
Official Documentation and Communities
- Official Python Documentation: A comprehensive resource for understanding Python's features and functionalities.
- Stack Overflow: A platform for searching for answers or asking questions related to Python.
- Python Tutor Mailing List: A community where you can ask questions and collaborate with other Python learners.
- Python-announce Mailing List: Stay updated with the latest developments and updates in the Python language.
Python's History and Evolution
- Initial Release: Python was first released almost 30 years ago.
- Language Evolution: Python continues to evolve with regular updates introducing new features, improving performance, and addressing security issues.
- Course Version: This course uses Python 3.7.
- Migration Tools: Python provides tools to help with code migration when new versions are released.
Additional Reading on Python's Growth and Trends
For those interested in the broader context of Python's growth and future trends, the following resources are recommended: