Welcome to Python 2!

Tips for navigating the slides:
  • Press O or Escape for overview mode.
  • Visit this link for a nice printable version
  • Press the copy icon on the upper right of code blocks to copy the code

Welcome!

Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.

Classroom "rules":

  • I am here for you!
  • Every question is important
  • Help each other
  • Have fun

Class series outline

This may change if we end up needing more or less time for certain topics.

  • Class 7: Review & reading from/writing to files
  • Class 8: More file operations, argument parsing & list comprehension
  • Class 9: Error handling
  • Class 10: HTTP requests
  • Class 11: Intro to Python frameworks & object-oriented Python
  • Class 12: Your own app with Django! (get data from an external API and create a visualization)

(note: Python 1 series included classes 1-6)

Class logistics

Introductions

Tell us about yourself:

  • Name
  • Preferred pronouns
  • Location
  • Programming experience & did you participate in the Python 1 class series?
  • What do you hope to learn in this class series?

Today's topics:

  • Repl.it coding environment
  • Quick review of Python 1 topics
  • Reading from/writing to files
  • Review final Python 1 exercise

Repl.it setup

Coding Python in Repl.it

Installing/running Python on lots of different systems/versions is tricky.

In this class, we'll use Replit, an online editor.

https://replit.com

Repl.it setup

  • Create a Replit account
  • Once you're logged in, create a new Python Repl
screenshot of repl

Using Replit

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).

screenshot of repl

Review from Python 1

Data types & structures

Simple data types

Data type Example values
Integers 2 44 -3
Floats 3.14 4.5 -2.0
Booleans True False
Strings '¡hola!' 'its python time!'
Name bound to value

Variables

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

Naming conventions for variables & functions

  • Use a lowercase single letter (variables only), word, or words
  • Separate words with underscores
  • Make names meaningful, ex first_name rather than fn


Examples

  • m (variables only)
  • hobby
  • my_fav_hobby

Data structures

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.

Lists

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]
                    

Tuples

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)
                    

Dictionaries

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!

Functions & methods

Built-in functions

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)
                    

Importing functions & modules

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)
                    

Built-in methods

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

Defining functions

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)
                    

Conditionals

Conditional statements

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"
                    

Comparison operators

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).

Logical operators

OperatorTrue 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

if/elif/else statements summary


                        def get_number_sign(num):
                            if num < 0:
                                sign = "negative"
                            elif num > 0:
                                sign = "positive"
                            else:
                                sign = "neutral"
                            return sign
                    

Syntax tips:

  • Always start with if clause.
  • Zero or more elif clauses.
  • Zero or one else clause, always at the end.

Loops

While loops

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
                    

For loop

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).

Looping through 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
                    

Loops in functions

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)
                    

Loops in functions


                    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)
                    

Python 1 materials

Find all the slides & exercises from Python 1 at
https://lizkrznarich.github.io/gdi-python-1

Working with files

CSV files

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
                    

Opening files

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
                    

See the docs on python.org for more

Reading files with CSV module

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)
                    

Reading files with CSV module

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)
                    

Exercise review: Reading from a CSV file

A simple grade calculator

Forking Replit files

  1. Click the link to the Replit, ex https://replit.com/@lizkrznarich/Class6Ex2CsvDataHeaders
  2. Click Fork Repl
  3. Click Edit in workspace

Writing CSV files

Writing files with CSV module

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)
                    

CSV files with headers

Reading CSV files with headers

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)
                    

Exercise review: CSV with headers

Let's re-visit our gradebook exercise...

Exercise: Multiple files

Get bits of data from multiple files and put it together into a nicely formatted report.

Feedback survey

Please fill out the GDI feedback survey to help us improve future classes. Thanks!