Tuples - Computer Science - Lecture Notes, Study notes of Computer Science

This is introductory course for computer science. Its about basic concepts involving in computer programming, structure and working. Key points in this lecture handout are: Tuples, Truncate, Erase Previous Contents, Immutable, Parenthesis in Tuples, Python

Typology: Study notes

2012/2013

Uploaded on 09/28/2013

noob
noob 🇮🇳

4.4

(25)

105 documents

1 / 5

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Lecture Notes CPSC 121 (Fall 2012)
Today
Quiz 8
File I/O (cont)
Tuples
Reading
Ch 14 pg. 125 (Tuples)
Ch 18 (Dictionaries)
S. Bowers 1 of 5
pf3
pf4
pf5

Partial preview of the text

Download Tuples - Computer Science - Lecture Notes and more Study notes Computer Science in PDF only on Docsity!

Today

  • Quiz 8
  • File I/O (cont)
  • Tuples

Reading

  • Ch 14 pg. 125 (Tuples)
  • Ch 18 (Dictionaries)

Writing to files

Use write() to add text to a file

  • Must open the file for “writing” ...

def main():

open test.txt for writing to

outfile = open("test.txt", "w") outfile.write("spam\n") outfile.write("ham\n") outfile.write("eggs\n") outfile.close()

echo contents of test.txt

infile = open("test.txt", "r") for line in infile: print(line[:-1]) infile.close()

  • If the file does not exist, will be created (when in "w" mode)
  • Opening again for writing will “truncate” the file (erase previous contents)
  • To append (add to end of file), use "a" instead of "w"
  • Instead of outfile.write("...") can use print("...", file=outfile)

Can only write strings

  • so to write numbers, must convert to strings first (via str())

What you can’t do with a tuple:

>>> t[0] = 15 ... TypeError: ’tuple’ object does not support item assignment

You can do tuple assignment ...

>>> (a, b) = (10, 20)

>>> a + b 30

Tuples often useful data structures ...

  • For example, we can use tuples to represent objects like (x, y) points
  • Tuples used in some Python functions, e.g., you can “zip” together two lists

>>> z = zip([10, 20], [’a’, ’b’])

>>> list(z) [(10, ’a’), (20, ’b’)]

You can create tuples of length 1

>>> t = (10,) >>> len(t) 1

The parenthesis in tuples are optional (but standard to use)

>>> t = 10, 20

>>> type(t)

>>> a, b = t

>>> a + b 30

  • You’ll sometimes see assignments like this in Python:

x, y = 10, 20

  • But can make code hard to read ...

Q: What about this?

>>> my_list = [20, 10]

>>> my_list[0], my_list[1] = my_list[1], my_list[0]

>>> my_list [10, 20]

Q: How does this work?

  • Right-hand side evaluates to (10, 20)
  • Then assignment is made