Skip to content
RayGutt edited this page Jan 16, 2020 · 3 revisions

Chapter 10 - Files and Exceptions

try except else blocks

Handling the FileNotFoundError Exception

common issue when working with files: handling missing files.

Analyzing Text

using the split() method to count the number of words in a text:

string -> split() -> list of strings of one word -> len()

Refactoring

good practice: a function should either return the value you're expecting, or it should return none.This allows us to perform a simple test with the return value of the function.

import json

def get_stored_username():
    """Get stored username if available."""
    filename = 'data/username.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_username():
    """Prompt for a new username."""
    username = input("What is your name? ")
    filename = 'data/username.json'
    with open(filename, 'w') as f:
        json.dump(username, f)
    return username

def greet_user():
    """Greet the user by name."""
    username = get_stored_username()
    if username:
        print(f"Welcome back, {username}!")
    else:
        username = get_new_username()
        print(f"We'll remember you when you come back, {username}!")


greet_user()

Chapter 11 - Testing Your Code

Write tests for your code. when you modify your code, use those tests to check that you didn't break your code. (non regression test) : unittest module

unit test: verifies that one specific aspect of a function's behavior is correct.

test case: a collection of unit tests that together prove that a function behaves as it's supposed to

# Print Python version
import sys
print(sys.version)
print(sys.version_info)
# Print the current date
import datetime
print(datetime.datetime.now())

# To format the date, use the strftime() method:
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
# Accepts the radius of a circle from the user and compute the area
radius = input("Please enter the radius of the circle: ")
area = 2 * 3.1415 * radius
print(f"The area : {area}")