Table 6-1 shows a summary of the differences between each collection.
Table 6-1. Collection similarities and differences
Data Collection Ordered Iterable
|
Unique Immutable Mutable
|
list Yes Yes
|
no no Yes
|
Dictionary no Yes
|
Keys only Keys only Values only
|
Tuple
|
Yes Yes
|
no Yes no
|
set
|
no Yes
|
Yes no Yes
|
Frozenset
|
no Yes
|
Yes Yes no
|
|
|
|
|
WEDNESDAY EXERCISES
|
1.
|
User Input: ask the user to input as many bank account numbers as they’d like, and store them within a list initially. once the user is done entering information, convert the list to a frozenset and print it out.
|
2.
|
Conversion: Convert the following list into a set of unique values. print it out after to check there are no duplicates:
>>> nums = [3, 4, 3, 7, 10]
|
Today we were able to view three other data collections. each one has a purpose, even though we mostly work with dictionaries and lists.
Thursday: Reading and Writing Files
Depending on the type of program you’re writing, you’ll need to save or access information. To do so, you’ll need to understand how to work with files, whether it be creating, writing, or reading.
To follow along with this lesson, let’s continue from our previous notebook file “Week_06” and simply add a markdown cell at the bottom that says, “Reading & Writing Files.”
Working with Text Files
By default, Python comes with an open() function that allows us to create or modify files. This function accepts two parameters, the file name, and the mode. If the file name exists, then it will simply open the file for modification; otherwise, it will create the file for you. The mode is in reference to how Python opens and works with the file. For instance, if you simply need to grab information from the file, you would open it up to read. This would allow you to work with the file while not accidentally changing it. Let’s look at how to open, write, and read text files:
1| # opening/creating and writing to a text file
2| f = open("test.txt", "w+") # open file in writing and reading mode
3| f.write("this is a test")
4| f.close( )
5| # reading from a text file
6| f = open("test.txt", "r")
7| data = f.read( )
8| f.close( )
9| print(data)
Go ahead and run the cell. Let’s walk through this line by line. We open the file in writing and reading mode for full editing and assign the value into the variable f. On line 3 we use the write() method to write our sentence to the file. Then we close the file. Anytime you open a file, you must always close it. After we’ve created and written to our test file, we open it back up in read-only mode. On line 7 we use the read() method in order to read all the contents of the file into a single string, which is assigned to our data variable. Then we output the info.
Note Mode “w” will overwrite the entire file. Use “a” for appending.
Do'stlaringiz bilan baham: |