Unit 3
Built in Functions
Can import third party library
How to create your own functions:
a function is a mini program
can give it data
Has a name
Has an argument (parameters) —> what data it can work with
Return value (what it spits out)
When you run a function
you can only access variables within that scope
when you’re using a fruitful function (returns a value) —> have to capture value
put it into a variable
print it
def nameOfFunction (input1, input2):
zz = input1 + input2
return zz ** 3
File stuff (I/O)
First save the file:
variableName = NameofText.txt
Open function
allows you to read the text file
f = open(variableName, ‘r’)
r is for read
Save whatever’s in the file into a variable
data = f.read()
f.close()
print(len(data)) —> tells you how many characters
print(data) —> prints what’s in the text document
How to clean data:
data = data.replace(‘ “ ‘, ‘ ‘) —> replaces “ with nothing
data = data.split(‘ , ‘) —> creates list on everything separated by , —> now it’s a list!
Going through the clean data
c = 0
for i = in data: #iterating through whole loop
c = c + 1
if i == ‘SARA’:
print(i,c) —> prints SARA and what number it is in the list
print(c) —> how many names are in files
with
implicitly opens and close
with open(“nameOfFile”, ‘r’) as f:
for line in f: #allows you to iterate through variable line
print(int(line)) #removes new line if you make it an integer
want to change the document
outputFile = open(“outnums.dat”, ‘w’) #w is for writing
with open (“numbers.dat”, ‘r’) as f:
for line in f:
print(int(line))
bump = int(line) + 1
of.write(str(bump) + ‘\n’)
12 —> 13
23 —> 24
of.close() #need this to write it down onto your hard drive
Libraries and Modularity
How to access functions that aren’t available to you
it’s in a standard library
math library has a lot of math functions
Have to load it
Import libraries
import nameOfLIbrary
import math
how to use a function from the library
nameOfLibrary.nameOfFunction(input)
If using from library import function —> you only get specific functions
does not need nameOfLibrary.nameOfFunction(input) —> you can just do nameOfFunction(input)
can not do reverse
you need to import all the functions AND need to remember which library