Exam 3
Assume you have a text file named my_file.txt. Fill in the blanks below so the code reads the file and prints each line of the text file. with open("my_file.txt", "________") as input_file: line = input_file.__________() while line != "": print(_______) line = input_file._______
"r", .readline() , line, .readline()
Function decomposition
A iterative process of breaking down the description of a big idea into finer and finer detail in which one function is described in greater detail by a set of other, supporting functions.
What is a side effect?
A side effect is when a function causes a change that is external to the function itself.
How is the data for each row in a CSV file stored once it is read?
As a list of things
Why do you need the import csv statement in the examples above?
Because csv.reader would generate an error if the import statement did not exis
Header variable
Can put the next command and store it into a header variable and print it, however it will still skip when iterating!
CSV
Comma separate files. They are similar to a spreadsheet in that data is stored in rows and columns and can be opened by spreadsheets programs. The first row is typically headers!!!!!
return value
Has to have a return within the indent, signifies the end of the function and passes a value back for when you call the function.
Is the variable or the value getting used as the arguments in functions calls.
ITS THE VALUE!!! That gets copied to the program, so you can use the same variable for the argument if you want.
writelines()
Is a method uses to write text to the file, any string of text passed to writelines() will appear in the file. ALWAYS CLOSE WHEN DONE!
How to read a CSV file?
Python needs to import the css module, it is then opened much like a text file but python needs needs to a run the file through a CSV reader.
What happens when Python tries to open a file in write mode, but the file does not exist?
Python will create a file
Two separate parts of function
The definition, and the function call
Read mode
Use "r" with opening a file. Read mode does not create a new file if the file does not exist, you only reader previously existing files.
Fill in the blanks the ________ mode will add new text to the file without erasing its contents. the _____ mode will overwrite the file with new text.
append and write.
open (command)
output_file = open("student_folder/text/practice1.txt", "W" This opens a folder in python, the output file is the variable it is stored into, and "w" is the mode.
readlines and reader for csv
you can use readlines and stuff with csv, just reader will take it as nested loop and allows you to deal with the columns better while readlines is just a list of all the data. READLINE LIKE FOR ALL IS A STRING OF ONE ROW/LINE OF DATA!
Core reasons why you want to use functions
1. Readability- It helps when the code isn't super long but is made up of shorter segments (especially if it has a descriptive name) 2. Re-usability- You can use the function repeatedly without having to use the same lines of code over and over again 3. It's hard to test a big program, but when you divide it into smaller components and test those and if those sub-components work, its more likely that the overall program works.
What is a file in python to the computer?
A collection of binary digits or "bits" like ones and zeros. 8 bits = 1 byte.
What is the purpose of a delimiter
A delimiter is a character that separates units of data.
Which of the following accurately describes a function definition in Python, based on the given description?
A function definition starts with the keyword def and is followed by the name of the function and its parameters enclosed in parentheses.
How does a function get information to do its job
Because variables in functions have local scope (not visible outside of the function) and variables in the main program are not visible to functions, the way a function gets information it needs to do its job is from the arguments passed to it at th time of the function call. THESE ARE CALLED PARAMETERS FROM THE FUNCTION POINT OF VIEW!
How are functions like a black box
Black box model= define inputs, go into black box where something happens, then it produces and returns an output (transformed information). In the grand scheme of things, it doesn't matter how you get to the output which is why its a black box.
Delimiters
By default, CSV files use commas the delimiter however you can change the delimiter when you set the reader variable like : reader = csv.reader(input_file, delimiter = "\t") You need to know the underlying structure of your data in order to determine which delimiter to use.
What is the difference? with open("my_file.txt", "r") as read_file: print(read_file.readlines()) with open("my_file.txt", "r") as read_file: for line in read_file.readlines(): print(line)
Code block 1 prints a list of strings. Code block 2 prints a "normal" looking text.
What is the difference between defining a function and calling a function?
Defining a function tells Python what actions the function will perform. Calling a function tells Python to perform those actions
What type of thing does each function have
Each function has its own local scope, meaning you can declare two variables with the same name as long as they are in separate functions. as the boundaries of local scope keep Python from overwriting the value of one variable with the contents of the second.
import csv with open("student_folder/csv/monty_python_movies.csv", "r") as input_file: reader = csv.reader(input_file) for row in reader: print(row)
Each row is a list!!!!!1
Function definition
Every function definition starts with a def, and usually start at the top of the program. Then you name it exactly like a variable, should describe what it does, it then can take parameters, these are variables that only exist in the scope of the function. They are like temp ones. This is in parentheses and separate in commas can have as many as you want, then end it with a. colon.
What is the return value for function that don't explicitly return something?
Every function returns something which is sometimes a value, however sometimes the function is just printing and a return doesn't need to be there but it will arise a problem when you try to save the value, you get none, these functions have a special return value called None which is of type NoneType. So if a function is just printing and you try to store it into x, x will just be none.
Functions are like nouns or adjectives in programming, while variables are more like verbs. True or False
False Variables are like noun as functions are like verbs, they are actions as they take information in the program, do something, then return transformed information.
What does this: output_file = open("student_folder/text/practice3.txt", "w") output_file.writelines("First sentence") output_file.close() And then what does this do when this is added: output_file = open("student_folder/text/practice3.txt", "a") output_file.writelines("Second sentence") output_file.close()
First sentenceSecond sentence
How to separate functions and the main program
For the ease of readability, its important to start writing the functions first and separate then from the main program with white space and a comment.
Function Vocab
Header: Def starts with this Name of function- after def follows rules of variable Set of parathenses- can have nothing or parameters then a colon Body: Does the action Return value= output what I needed.
What will the following program print? def greet_twice(): greeting1 = "Hello" greeting2 = "Hola" print(greeting1) print(greeting2) greeting1 = "Aloha" greeting2 = "Bonjour" greet_twice() print(greeting2)
Hello Hola Bonjour
Why must you close a file?
If you forget to close it, and for example open a file with newly written text. The text may not be in the file.
Unpacking
If you know how many different columns known you can create a variable for each element and print it like it looks like. : for name, hr, active in reader: print("{} hit {} home runs.".romate(namer)) This will create a variable for each element, however you must have the same number of variables in the loop as there are elements in the list.
Multiple next commands
If you use two next commands, it will skip the first two.
Newlines and write-ins
If you want the text to appear on a new line, you need to use a newline character "\n"
Can you a write a function that returns a list?
If you want to return a list, it is a good idea to have a list be passed as a parameter. Create a new list that modifies the old list in the someway and then return said list. def mult_by_5(my_list): '''Takes a list of ints and returns a new list where each element is multiplied by 5''' new_list = [] for elem in my_list: new_list.append(elem * 5) return new_list print(mult_by_5([1, 2, 3, 4, 5]))
What is the purpose of the "return" statement in a function in Python?
It allows the function to pass back a value to the calling code.
What does readlines() return?
It returns a list of strings, with each string in the list representing a line of the file. \n is included at the end of each element.
What is different withe append mode.
It will also create a file is one does not already exist, however append mode will not erase content already saved to the file. It will add the text to the end of the file.
is there is a backslash in a file what do you have to do when using it?
Make sure to do a double backslash!!!!!
Does defining a function cause python to run it?
No! You need to explicitly call the function if you want it run. you call it by the name and parathesses, and in the parethensees is any variables you need to pass to the corredponsidng parameters. greet_twice()
What happens to a print statement after a return statement
Nothing happens after a return statement.
Look at the function definition and the function call below, and then answer the questions. def add_nums(num1, num2): """Prints the sum of two numbers""" print(num1 + num2) add_nums(7, 35)
Num2 = 35 Num1 = 7
Select all of the data types that can be passed to a function as a parameter. Note, there is more than one correct answer.
Numbers (floats or ints) Strings Booleans Lists of strings, numbers, or booleans
What does this print? lines_to_write = ["One upon a time\n", "In a land far, far away\n", "Lived a king and queen\n"] output_file = open("student_folder/text/practice2.txt", "w") output_file.writelines(lines_to_write) output_file.close()
One upon a time In a land far, far away Lived a king and queen
Order of functions definitions and calls
Order matters, you can 't call a function before it's defined. INDENTATION ALSO MATTERS!!!!
What does pass mean?
Pass is a placeholder for a statement or statement to be filled in later, We know that the function needs to do something or else an error message will appear, but we haven't written that code yet. Using pass means that the function will not do anything, but there will not be an error message either.
readlines
Print the contents of a text file, use the readlinesmethod it look likes read_file.readlines()
What is the biggest difference between read mode and write/append modes when referencing a file that does not exist?
Reading a file that does not exist will cause an error. Writing or appending a file that does not exist will cause the creation of this file.
How do you tell Python that your function declaration is done?
Remove the indentation Python uses whitespace to differentiate between normal code and a function definition. Code for a function definition is indented (4 spaces is convention). Once code no longer has this indentation, the function definition is done. Blank lines have no affect on how Python interprets your code. Though blank lines can make your code easier to read for humans.
What does the return keyword do?
Returns a value calculated by a function back to the program.
Readline method
Returns only one line from the text file. Python automatically keeps track of which lines have been read and which have not.
How to get rid of the empty lines?
So print(line,end="") in the for loop, this will remove the plank line. It replaces the newline character with an empty string.
file format
The computer knows what type of file it is though file extension such as .doc, .txt, .jpg or .mp3. A cue to the program of how to handle the information. The binary digits are interpreted by the file.
What two arguments are passed to the open command?
The file to be opened and the mode
next command
The first row is helpful because the header values provide context for the data. However the first first row isn't useful if you want to know how many rows of data or calc the ag. the next command allows python to skip the first row before looping through thhe CSV file and it looks like next(reader)
What happens if you don't stop indenting after defining the function
The main code will be in the scope of the function
When making changes to the parameter values inside a function, how are the original arguments affected?
The original arguments remain unchanged.
What happens with a return value in the main program memory.
The return value isn't stored into the memory of the main program so if you wanted to reuse that specific return value you need to store it in a variable.
Different between saying text[0] or print(text) text = [] with open("student_folder/.labs/files-lab1.txt", "r") as input_file: text = input_file.readlines() print(text[0]) print(text[0].upper())
The variable text is a list of strings. If you print text, it will print the entirety of the list — including square brackets and quotes. Printing text[0] will print just the text, no special characters.
With open
The with open command combines the two lines of code that open and close the file. it looks like this: with open("file"."a") as output_file: output_file.writlines The as output_file is the file variable and there's a semi colon and indent like with loops. Any code not indented is not counted.
Three modes
There a three different modes when opening a file: read = "r" write = "w" append = "a"
What are arguments in function calls.
These are the values sent to a. function through a function call, their values or it itself if not a variable get copied and assigned to the functions parameters
Are side effects bad?
They are not bad and sometimes they may be the desired result. However, the more side effects a function produces, the greater risk of introducing a big. When thinking about the functions you are writing, if possible, break up your code into several smaller functions and only introduce side effects when necessary to limit this risk and time spent on debugging.
Types of parameters values
They can be the same values as variables: ints, floats, strings, boolean, lists, etc it just needs to work in the function! Match arguments values with types of parameters.
what does output_file.close()
This closes a file.
Calling variables in the function in the main program
Those variables won't be able to call bc it only exists in the function! So you should try to get that variable from the return value and store that into another variable. It does this bc it manages memory and sets the memory aside when it knows it doesn't need it in the subprogram.
_________ declared inside a function have ______ scope. This means you can only reference the variable from ______ the function. Trying to reference the variable from _______ the function will cause an error.
Variables local inside outside
While loop and deadline
When equal to "", python knows it has reached the end of the file. it looks like: with open("student_folder/text/read_practice.txt", "r") as read_file: line = read_file.readline() while line != "": print(line) line = read_file.readline()
When is a function call doing
When it is called, the program breaks from the main code then does the function code and then after that it does it returns to the main code.
Extra lines
When printing a line, there is an empty line between lines of text. This is because pf the \n at the end of each line (Except last one) and the print command automatically adding a newline character.
Reading a file multiple times
When python reaches the end of a file with readlines, it will not start back at the beginning until you close the file and reopen it SO YOU CANT REITERATE TWICE WITHIN ONE WITH OPEN!
What does this do: output_file = open("student_folder/text/practice1.txt", "w") output_file.writelines("Hello there") output_file.close()
Will open the file, write Hello there and then close it. Hello there will appear on the file.
for row in reader: print(row[0], row[1], row[2])
You can print a row without it looking like a list by doing this.
Passing information through the function call
You can technically pass any variables but make sure it's the right type. THESE ARE CALLED ARGUMENTS!!! It has to match the parameters so if the function is def numbers(a,b,c,d) and you call with it numbers(1,2,3,4). Then in the scope of the program, a becomes 1 and b = 2 and c = 3 and d =4
Parameters as Variables
You can think of them as variables, declared in the function header and assigned when called. Because of this order is important, the first argument in the call will be assigned to the first parameter in the function header and etc.
writelines() lists
You can use a list of strings with the writelines() method, made sure to add spaces if you want space.
writing with cvs
You can use the "w" in cvs, it will create a file if it doesn't exist already. pass it through a writer like cvswriter = cvs.writer(file). You then use methods like .writerow() and .writerows(). writer is a list while writers is a nested list. Make sure to add newlines can expect a variable that is a list too, writerow usually helps with header.
File location
You need to exactly where the file is to use it. By default it looks in the folder where the python is being run. Absolute: start at the root like c:\Documents\myfile.txt or The relative path which a navigation path from the current place where the file is being run to another.
read()
a function that reads all the contents of a lien and when you print it it will print like normal unlike readlines() which prints a whole list doesn't help much when iterating and needed to do stuff with the lines tho.
What is a parameter
a placeholder in a function definition that defines what information the functions expects when it is called. An argument is the actual information sent to the function.
How does a function definition look like
def calculate_area(length, width): area = length * width return area
The code below has a side effect (printing). def has_letter_a(word): if "a" in word: print("{} has the letter 'a' in it.".format(word)) else: print("{} does not have the letter 'a' in it.".format(word)) has_letter_a("apple")
def has_letter_a(word): if "a" in word: return("{} has the letter 'a' in it.".format(word)) else: return("{} does not have the letter 'a' in it.".format(word)) print(has_letter_a("apple"))
Example of side effects
global variable, controlling some external device, printing to the screen, writing to a file, etc.
What does this appear output_file = open("student_folder/text/practice2.txt", "w") output_file.writelines("Hello") output_file.writelines("there") output_file.close()
hellothere
Assume there exists a tab delimited CSV file called data.csv. The CSV file has two columns of data: a name and a color. There is no header row in the CSV file. Rearrange the code blocks below so that the program reads the file and uses the information from each row to generate a sentence like this: Patrick's favorite color is blue.
import csv with open("data.csv", "r") as input_file: reader = csv.reader(input_file, delimiter="\t") for name, color in reader: print("{}'s favorite color is {}.".format(name, color))
Assume that you have a comma delimited file called data.csvRearrange the code blocks below to read the file and print the contents line by line. Note, not all of the code blocks will be used. Also remember that indentation is important in Python, so indent appropriately.
import csv with open("data.csv", "r") as input_file: reader = csv.reader(input_file) for row in reader: print(row)
What does pass do?
pass allows you to have a function header but acts as a placeholder for the function body until you write it.
Assume the variable input_file is an opened CSV file. How would you declare the the csv.reader to indicate that the CSV file uses the ! character as the delimiter?
reader = csv.reader(input_file, delimiter="!")
Fill in the blanks: The ________ method reads all of the text file and returns all of the strings in a list, which you can then iterate through using a ______ loop that stops when the end of the list is reached. The _________ method reads one string at a time, so you can iterate through the file using a _____ loop that stops when the end of the file is reached.
readlines for loop readline while loop
Readlines and loop
readlines returns all the text at once as a big list, with each element a list. A loop allows you to deal with each lune individually.
How does the file path of practice1.txt look like if you have to : 1. go to student folder 2. go to text folder 3. then go to practice1.txt
student_folder/text/practice1.txt
Assume there is a text file named hand_grenade.txt. Rearrange the code blocks below to create a program that will add the following text to the file. Your program should not alter any information already in the text file. And Saint Attila raised the hand grenade up on high, saying, "O Lord, bless this Thy hand grenade that, with it, Thou mayest blow Thine enemies to tiny bits in Thy mercy."
with open("hand_grenade.txt", "a") as output_file: output_file.writelines('And Saint Attila raised the hand grenade up on high, saying, ') output_file.writelines('"O Lord, bless this Thy hand grenade that, with it, ') output_file.writelines('Thou mayest blow Thine enemies to tiny bits in Thy mercy."')
Assume you have a text file called story.txt. Rearrange the code blocks below so that the program will print the text file as you would expect it to appear. Note, not all of the code blocks will be used.
with open("story.txt", "r") as input_file: lines = input_file.readlines() for line in lines: print(line, end="")
Rearrange the code blocks below to create a program that writes the following information to the file tongue_twister.txt. Peter Piper picked a peck of pickled peppers A peck of pickled peppers Peter Piper picked If Peter Piper picked a peck of pickled peppers Where's the peck of pickled peppers Peter Piper picked?
with open("tongue_twister.txt", "w") as output_file: output_file.writelines("Peter Piper picked a peck of pickled peppers\n") output_file.writelines("A peck of pickled peppers Peter Piper picked\n") output_file.writelines("If Peter Piper picked a peck of pickled peppers\n") output_file.writelines("Where's the peck of pickled peppers Peter Piper picked?\n")
How does a for loop with readlines look like?
withopen("student_folder/text/read_practice.txt", "r") as read_file: file_contents=read_file.readlines() for line in file_contents: print(line)