Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.
Classroom "rules":
This may change if we end up needing more or less time for certain topics.
(note: Python 1 series included classes 1-6)
Tell us about yourself:
Installing/running Python on lots of different systems/versions is tricky.
In this class, we'll use Replit, an online editor.
Type code in the left panel (main.py file) & click "Run". Output is shown in the right panel (console).
You can also type code directly in the console panel (press Enter key to run).
Data type | Example values |
---|---|
Integers | 2 44 -3
|
Floats | 3.14 4.5 -2.0
|
Booleans | True False
|
Strings | '¡hola!' 'its python time!'
|
A name can be bound to a value.
A name that's bound to a data value is also known as a variable.
One way to bind a name is with an assignment statement:
x | = | 7 |
Name | Value |
The value can be any expression:
x | = | 1 + 2 * 3 - 4 // 5 |
Name | Expression |
first_name
rather than fn
m
(variables only)
hobby
my_fav_hobby
A data structure is a particular way of organizing data in a computer so that it can be used effectively.
Data structures in programming are a bit like lists and tables in text docs/presentations - we use them to organize information and make it more meaningful/useful.
A list is a container that holds a sequence of related pieces of information.
Lists can hold any Python values, separated by commas:
# all strings
members = ["Liz", "Tinu", "Brenda", "Kaya"]
# all integers
ages_of_kids = [1, 2, 7]
# all floats
prices = [79.99, 49.99, 89.99]
# mixed types
mixed_types = ["Liz", 7, 79.99]
A tuple is like a list, but immutable: its values cannot be changed after the initialization.
Tuples are enclosed in parentheses (9.99, 7.99, 3.99)
position = (100, 50)
prices = (9.99, 7.99, 3.99)
A dict
is a mutable mapping of key-value pairs
states = {
"CA": "California",
"DE": "Delaware",
"NY": "New York",
"TX": "Texas",
"WY": "Wyoming"
}
Dictionaries allow you to access values using a human-readable name ("key") rather than an index number. Dictionaries map very well to JSON!
Python has lots of built-in functions. Built-in functions are not specific to a particular data type - they often work on multiple data types (but check the docs!)
Some examples are:
pow(2, 100)
max(50, 300)
min(-1, -300)
Some functions from the Python standard library are available by default. Others are included with a basic Python installation, but need to be imported into your current file before they can be used.
Import a single function from the Operator module :
from operator import add
18 + 69
add(18, 69)
Each data type has a set of built-in methods that only work on that data type. Check the Python data types docs to see which methods are available for a given data type.
Examples of string methods are:
Function | Description |
---|---|
.upper() | Returns a copy of the string with all characters converted to uppercase |
.lower() | Returns a copy of the string with all characters converted to lowercase |
.title() | Returns a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase |
.swapcase() | Returns a copy of the string with uppercase characters converted to lowercase and vice versa |
.strip() | Returns a copy of the string with the leading and trailing whitespace characters removed |
We define functions in Python with a def
statement.
def <name>(<parameters>):
return <return expression>
Example:
def add(num1, num2): # ← Function signature
sum = num1 + num2 # ← Function body
return sum # ← Function body
Once defined, we can call it:
add(2, 2)
add(18, 69)
A conditional statement gives you a way to execute a different set of code statements based on whether certain conditions are true or false.
if <condition>:
<statement>
<statement>
...
A simple conditional:
clothing = "shirt"
if temperature < 32:
clothing = "jacket"
Operator | Meaning | True expressions |
== | Equality | 32 == 32
|
!= | Inequality | 30 != 32
|
> | Greater than | 60 >= 32
|
>= | Greater than or equal | 60 >= 32 , 32 >= 32
|
< | Less than | 20 < 32
|
<= | Less than or equal | 20 < 32 , 32 <= 32
|
⚠️ Common mistake: Do not confuse =
(the assignment operator) with ==
(the equality operator).
Operator | True expressions | Meaning |
---|---|---|
and | 4 > 0 and -2 < 0 | Evaluates to True if both cconditions are true; otherwise evaluates to False .
|
or | 4 > 0 or -2 > 0 | Evaluates to True if either condition is true; evaluates to False only if both are false.
|
not | not (5 == 0) | Evaluates to True if condition is false; evaluates to False if condition is true.
|
W3Schools has a handy Python operators reference
def get_number_sign(num):
if num < 0:
sign = "negative"
elif num > 0:
sign = "positive"
else:
sign = "neutral"
return sign
Syntax tips:
if
clause.
elif
clauses.
else
clause, always at the end.
The while loop syntax:
while <condition>:
<statement>
<statement>
As long as the condition is true, the statements below it are executed.
multiplier = 1
while multiplier <= 5:
print(9 * multiplier)
multiplier += 1
The other type of loop supported in Python is a for
loop
The for loop syntax:
for <value> in <sequence>:
<statement>
<statement>
For loops provide a clean way of repeating code for each item in a data structure (like a list).
😍 For loops love lists!
scores = [80, 95, 78, 92]
total = 0
for score in scores:
total += score
This does the same thing as a while
loop with a counter, but with less code.
scores = [80, 95, 78, 92]
total = 0
i = 0
while i < len(scores):
score = scores[i]
total += score
i += 1
A loop in a function will commonly use a parameter to determine some aspect of its repetition.
def sum_up_squares(start, end):
counter = start
total = 0
while counter <= end:
total += pow(counter, 2)
counter += 1
return total
sum_up_squares(1, 5)
def calculate_average(scores):
total = 0
for score in scores:
total += score
return total / len(scores)
scores = [80, 95, 78, 92]
average_score = calculate_average(scores)
Find all the slides & exercises from Python 1 at https://lizkrznarich.github.io/gdi-python-1
Comma Separated Value (CSV) is a plain text format used to store "tabular" data (aka rows and columns), like from a spreadsheet or database table.
Because CSV is simple and non-proprietary, it's commonly used to exchange data between different applications.
Brittany, 9.15, 9.4, 9.3, 9.2
Lea, 9, 8.8, 9.1, 9.5
Maya, 9.2, 8.7, 9.2, 8.8
We use the Python built in open()
method to open files for reading or writing.
The keyword with
tells Python to automatically close the file when we're finished.
with open('filename') as my_file:
# do something
Python has a built-in CSV module that includes many features used for reading/writing CSV files.
Open a CSV and read its contents (docs at python.org)
# import the csv module
import csv
# open the file
with open('fun_spreadsheet.csv') as my_file:
# load the contents of the CSV file into a variable
csv_reader = csv.reader(my_file)
# CSV is a nested list!
# now we can loop through the rows in the file
for row in csv_reader:
print(row)
A CSV is a list of rows, which are lists of values.
We can use nested for loops to get values from rows and cells.
import csv
with open('fun_spreadsheet.csv') as my_file:
csv_reader = csv.reader(my_file, delimiter=',')
for row in csv_reader:
print(row)
for cell in row:
print(cell)
A simple grade calculator
The CSV module also has support for writing files (docs)
import csv
my_list = [
["Mon", "Oatmeal", "Salad", "Pasta"],
["Tues", "Waffles", "Soup", "Tacos"],
["Wed", "Cereal", "Sandwich", "Pizza"]
]
# open a new or existing file for writing
with open('fun_spreadsheet.csv', 'w') as my_file:
# prepare the CSV for writing
writer = csv.writer(my_file)
# write data from a list to the CSV file
writer.writerows(my_list)
Use csv.DictReader to read a CSV file with headers
# import the csv module
import csv
# open the file
with open('fun_spreadsheet.csv') as my_file:
# load the contents of the CSV file into a variable
csv_reader = csv.DictReader(my_file)
# CSV read as dict with column headers as keys!
# now we can loop through the rows in the file
# and get the values from specific columns
for row in csv_reader:
print(row)
Let's re-visit our gradebook exercise...
Get bits of data from multiple files and put it together into a nicely formatted report.
Please fill out the GDI feedback survey to help us improve future classes. Thanks!