Python 1-3#
Functions, documentaion, strings, files
Functions#
defto create your functioncalling your function (arguments)
docstrings
named arguments
What are functions?#
A Function is a named sequence of statements which accomplish a task. They promote modularity, making our code less complex, easier to understand and encourage code-reuse.
When you “run” a defined function it’s known as a function call. Functions are designed to be written once, but called many times.
We’ve seen functions before:
1# We call functions all the time
2# input(). random.randint(), and int() are all functions!
3import random
4x = input("Enter Name: ")
5y = random.randint(1,10) #random is the module, randint() is the function
6z = int("9")
7print(x,y,z)
tony 4 9
Function Definitions#
Functions are like their own little programs. They take input, which we call the function arguments (or parameters) and give us back output that we refer to as return values.
INPUT -=> PROCESS ==> OUTPUT
Function ==> Function ==> Function
Arguments Definition Return
1# Example Function
2def area_of_triangle(base, height): # <== INPUTs
3 area = 0.5 * base *height
4 return area # <== OUTPUT
5
6# Function call: using your function
7a = area_of_triangle(10,5)
8print(a)
25.0
1# When you call a function you can name your arguments:
2# This allows you to override the order of the arguments
3
4# These are the same order as defined
5area1 = area_of_triangle(base=10, height=5)
6# Different order than defined
7area2 = area_of_triangle(height=5, base=10)
8print(area1, area2)
25.0 25.0
Challenge 1-3-1#
Write a function called average which takes a list of numbers as input then outputs the average of the numbers sum / count
Call your function with an arbitrary list of numbers you create.
Type Hints#
Types can be added to the def statement to help the caller understand what type of data the function expects. These are known as type hints
In this example the expected arguments are float and the return is float
1def area_of_triangle(base: float, height: float) -> float:
2 area = 0.5 * base *height
3 return area
You can see type hints in action by calling the function
Run the cell above to create the function.
In the code below, start a left paren ( to see the type hints
1area_of_triangle
Docstrings#
A Docstring is a multi-line comment which explains what the function does to the function caller.
The same function with type hints and docstring:
1def area_of_triangle(base: float, height: float) -> float:
2 '''
3 Calculates the area of a triangle given base and height
4 returns the area defined as 1/2 the base times height
5 '''
6 area = 0.5 * base *height
7 return area
You can see doc strings in action by calling the function
Run the cell above to create the function.
In the code below, start a left paren ( to see the doc string
1area_of_triangle
Strings#
string slices
string methods
text processing
String are sequence types#
You can use slice notation like with lists.
These are zero based.
var[start:stop]
Takes stop - start characters from var starting at position start
1x = "fudge"
2print(x[0:2]) # fu
3print(x[2:5]) # dge
4print(x[:4]) # fudg
5print(x[:]) # fudge
6print(x[:-1]) # fudg
fu
dge
fudg
fudge
fudg
String Methods#
https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str
Method functions attach to the string x.strip()
Common methods
strip()
upper()
lower()
find()
count()
split()
join()
replace()
1# Samples
2s = "this is a test"
3print(s.count("is")) # 2
4print(s.count("t")) # 3
5print(s.upper()[:4]) # TEST
6print(s.find(" a ")) # 7
7print(s.find("this")) # 9
8print(" x ".strip()) # x
9print(s.replace("this","that")) # that is a test
2
3
THIS
7
0
x
that is a test
Challenge 1-3-2#
Write a function called cleanup which takes a string as input and returns a “cleaned string” meaning:
remove any ? , . or !
strip off the whitespace from the ends
return text in lower case
write code to call your function and test it
String Tokenization and Parsing#
Tokenization is the process of breaking up a string into words, phrases, or symbols.
Tokenize a sentence into words.
"mike is here"becomes the iterable['mike','is','here']
Parsing is the process of extracting meaning from a string.
Parse text to a numerical value or date.
int('45')becomes45
1# tokeniize with split()
2# parse with int(), or float()
3
4text = "30 40 90 10"
5tokens = text.split()
6numbers = [int(t) for t in tokens]
7total = sum(numbers)
8print(total)
170
1# What you split on is called the delimiter:
2text = "name, age, phone, gpa"
3items = [ x.upper().strip() for x in text.split(',') ]
4print(items)
['NAME', 'AGE', 'PHONE', 'GPA']
Files#
withstatement / context managerreading / writing text files (all at once, line at a time)
JSON serialization / de-serialization
Files == Persistence#
Files add a Persistence Layer to our computing environment where we can store our data after the program completes.
Think: Saving a game’s progress or saving your work!
When our program Stores data, we open the file for writing.
When our program Reads data, we open the file for reading.
To read or write a file we must first open it, which gives us a special variable called a file handle.
We then use the file handle to read or write from the file.
The read() function reads from the write() function writes to the file through the file handle.
1# Reading From a file...
2filename = "data/sample.txt"
3print("=== All at once ===")
4with open(filename, 'r') as handle:
5 contents = handle.read()
6 print(contents)
7
8print("=== A Line at a time ===")
9i = 1
10with open(filename, 'r') as handle:
11 for line in handle.readlines():
12 print(i, line.strip())
13 i += 1
=== All at once ===
This
Is
A
Sample
=== A Line at a time ===
1 This
2 Is
3 A
4 Sample
1# Writing to a file
2filename = "data/demo.txt"
3print("=== Create file and write to it ===")
4with open(filename, "w") as f:
5 f.write("message!\n")
6
7print("=== Append (add to end) of existing file ===")
8with open(filename, "a") as f:
9 f.write("message # 2!\n")
10
=== Create file and write to it ===
=== Append (add to end) of existing file ===
1!cat demo.txt
message!
message # 2!
1# Try / Except to handle FileNotFound
2try:
3 file = 'data/data.txt'
4 with open(file,'r') as f:
5 print( f.read() )
6except FileNotFoundError:
7 print(f"{file} was not found!")
data/data.txt was not found!
JSON and Python Dictionaries#
JSON (JavaScript Object Notation) is a standard, human-readable data format. It’s a popular format for data on the web.
JSON Can be easily converted to lists of dictionaries using Python’s json module.
Transferring a JSON string to Python is known as de-serializing.
Transferring Python to a JSON string is known as serializing.
This is easy to do in Python but challenging to do in most other languages.
1# Serialize a python object as json
2import json
3grades = { 'CHE101' : [100,80,70], 'IST195' : [100,80,100] }
4with open("data/grades.json", "w") as f:
5 json.dump(grades, f, indent=4) # write grades to file as JSON
1!cat data/grades.json
{
"CHE101": [
100,
80,
70
],
"IST195": [
100,
80,
100
]
}
1# de-serialize some json
2file = "data/stocks.json"
3with open(file, "r") as f:
4 stocks = json.load(f)
5
6# stocks is a python object
7# Deserialized from text!
8for stock in stocks:
9 print(stock['symbol'])
AAPL
AMZN
FB
GOOG
IBM
MSFT
NET
NFLX
TSLA
TWTR
Challenge 1-3-3#
write a program to read in a string of students and gpas in one input statement like this:
mike 3.4, noel 3.2, obby 3.5, peta 3.4
and write out JSON like this:
[
{ "name" : "mike", "gpa" : 3.4 },
{ "name" : "noel", "gpa" : 3.2 },
{ "name" : "obby", "gpa" : 3.5 },
{ "name" : "peta", "gpa" : 3.4 }
]
Suggested approach:
1. input text
2. for each student split on "," from the text
3. split the student into name and gpa
4. parse the gpa so its a float
5. add the name and gpa to the list
6. write the list to students.json as JSON