-
Notifications
You must be signed in to change notification settings - Fork 0
Home
RayGutt edited this page Jan 16, 2020
·
3 revisions
try except else blocks
common issue when working with files: handling missing files.
using the split() method to count the number of words in a text:
string -> split() -> list of strings of one word -> len()
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()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
Notes from https://www.w3resource.com/python-exercises
# 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}")