Learn Python With Me

Learn Python With Me

A Python Course for Beginners in Programming

Jitsi Meet (online meeting link)
Telegram (Q&A)
GetTogether (community)

Support my work
If you find this course useful, you can support my work by making a donation on Paypal.


Course outline

Learn Python With Me #6

May 13, 2020
The csv module — reading and writing CSV files. Handling errors in programs.

expense.csv

Number,Item,Cost
1,Milk,1.49
2,Coffee,1.97
3,Bread,1.49
4,Pizza,2
5,Pet food,4.75

Script 1: read_csv.py

import csv

with open("expense.csv", newline="") as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row[0], row[1], row[2])

Script 2: read_csv_total.py

import csv

with open("expense.csv", newline="") as csvfile:
    reader = csv.reader(csvfile)
    next(reader)

    total = 0
    for row in reader:
        print(row[0], row[1], row[2])
        total += float(row[2])
    print("Total cost: ", total)

Script 3: read_csv_dict.py

import csv

with open("expense.csv", newline="") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row["Number"], row["Item"], row["Cost"])

Script 4: read_csv_dict_total.py

import csv

with open("expense.csv", newline="") as csvfile:
    reader = csv.DictReader(csvfile)

    total = 0
    for row in reader:
        print(row["Number"], row["Item"], row["Cost"])
        total += float(row["Cost"])
    print("Total cost: ", total)

Script 5: read_csv_handle_error.py

import csv

with open("expense_invalid.csv", newline="") as csvfile:
    reader = csv.DictReader(csvfile)

    total = 0
    for row in reader:
        print(row["Number"], row["Item"], row["Cost"])
        try:
            total += float(row["Cost"])
        except ValueError:
            print("ERROR: Invalid entry for cost on Line", row["Number"])
        else:
            print("Total cost: ", total)

Learn Python With Me #5

April 29, 2020
Reading and writing text files

Reading a file involves

  1. Opening file
  2. Reading a line (or lines) from file
  3. Closing file

Sample code demonstrating steps above:

f = open("sample.txt", "r")
line = f.readline()
f.close()

The open() function (line 1) is used for opening a file with the file name as the first argument - sample.txt in this case. The mode in which the file has to be opened is provided as the second argument. Here the file is opened read only (r). The function returns a file object which is stored in variable f.

In the second line, the readline() method of the file object can be used to read a single line from the file. Calling readline() again will read the next line of the file and so on until the end of file is reached.

Finally, the file has to be closed using the close() method to free system resources.

To read all lines from a file, use readlines():

lines = f.readlines()
print(lines)
["This is line 1\n", "This is line 2\n", "This is line 3\n"]

lines will now be a list containing all lines in the file.

The \n at the end of each line is called as a newline character and is used to indicate where a line ends in a file. To remove this character, the str.strip() method can be used:

new_lines = []
for line in lines:
    new_lines.append(line.strip())
print(new_lines)
["This is line 1", "This is line 2", "This is line 3"]

To create (write) a new file

The steps are similiar to reading a file. Use the w mode to the open() function. Please note, the file will be overwritten if it already exists.

data = ["one", "two", "three"]
f = open("sample-write.txt", "w")
for item in data:
    f.write(item + "\n")
f.close()

To append data to an existing file

Use the a mode to the open() function. Data will be added to the end of the file.

data = ["four", "five"]
f = open("sample-write.txt", "a")
for item in data:
    f.write(item + "\n")
f.close()

To read files with large amount of data

Rather than reading all data from a file at once using readlines(), consider using the open() function in combination with a for loop.

large_file = "some_file.txt"
for line in open(large_file):
    # process line
    print(line)

For more information, on reading and writing files, please consult the Input and Output section of the Python tutorial.


Learn Python With Me #4

April 22, 2020
More on looping techniques, functions

A while loop executes statements inside the block as long as the condition is true. For example, consider the following code:

number = 0
while number != 10:
    number = int(input("Enter number: "))
print("Done")

When you save and run this code, you will be prompted to enter a number (line 3). If you enter a number other than 10, the condition number != 10 will be true and the while loop will then continue asking for new input.

When you enter the number 10, the while loop completes and the “Done” message will be printed.

A function is a series of statements which returns some value to a caller. It can be passed zero or more arguments which may be used in the execution of the body (source)

Here is a simple function to add two numbers:

def add_numbers(a, b):
    print(a + b)

The def keyword is used to define a new function followed by a name for the function - add_numbers in this case. It takes two numbers (a, b) as arguments and then prints their sum.

To call the function, use:

add_numbers(2, 3)

This will output 5.

An advanced example: currency.py

This script has a function defined called as convert which converts Euro to USD using a set exchange rate. When run, the script will prompt user to enter amount in Euro, do the conversion to USD, add it to a total amount and then print it.

# Convert currency from EUR
def convert(amount, currency="USD"):
    rates = {"USD": 1.08150, "GBP": 0.87865}
    if currency not in rates:
        print(f"{currency} not supported")
        return

    result = amount * rates[currency]
    print(f"Amount in {currency}: {result:.2f}")
    return result


if __name__ == "__main__":

    total = 200
    # Ask user for amount in Euro
    amount = int(input("Enter amount (EUR): "))
    amount_usd = convert(amount=amount, currency="USD")

    total += amount_usd
    print(total)

The return statement in the function is used to return the calculated result.

To convert the Euro amount to GBP, call the convert function like so:

amount_gbp = convert(amount=amount, currency="GBP")

Learn Python With Me #3

April 15, 2020
Tuples, Dictionaries, if statement, for loop.

Slides
Zeal offline documentation browser.


Learn Python With Me #2

April 1, 2020
Working with strings, reserved keywords, working with lists, accessing list elements, the dir() and len() functions.

Slides
Python 3 documentation


Learn Python With Me #1

March 25, 2020
Introduction to Python, why use it?, the Mu editor, REPL/Python interpreter. Basic syntax, variables, functions, data types, comments.

Slides

Temperature conversion program: c2f.py

# Convert temperature in celsius to fahrenheit

# temp_c = 8
temp_c = input("What is the temperature today? ")
print("Temperature in celsius is ", temp_c)

# F = 1.8 x C + 32
temp_f = 1.8 * temp_c + 32
print("The temperature in Cork today (F) is ", temp_f)

Notes

Using Python 3’s f-string syntax, the above print statement can be written as:

print(f"The temperature in Cork today (F) is {temp_f}")