Python Resources

Updated on July 16  2014

Python Class Notes

Deborah R. Fowler



Python Notes

Updated on April 27  2013

click here for Python Resources


Continuing concepts on Python (for introductory concepts see Turtle Graphics section)
Note: This page was created specifically for VSFX 705 Spring 2013.


So far we have covered variable, truth statements (selection), looping and functions. Next we'll look at lists, file i/o and finally oop.
These examples are taken from various web sources listed on the Python Resources page and are used only for in-class exercises.

Console I/O

name = raw_input("What is your name?")         #   raw_input  - input a string from the keyboard
print "Hi " + name + "! How are you?"              #   strings are concatenated with +
print "My name is ", name                                  #   can also use , to print beside


number = input("Input a number ")                    #   input is used to input numeric values

Exercises to try: (answer key here)


Strings

Delimited by double quotes “    Special characters \n is a newline \t is a tab.To print them use a backslash. Multi-line print is enclose in three double quotes “””…”””.

print "To print a newline use \\n"

print "So for \nexample"

print "\t we can indent too"

print """

Many

Many

Many

lines

"""

 
Exercise to try:



\  |  /

0         0

    -

              \____/

 


String operators

a = b + c                                concatenate

a = b * c                                b repeated c times

a[0]                                        first character of a

len(a)                                    number of characters in a


Exercise to try:
Write a program that prints a word in a rectangle using + and *

ie.        hello     hello     hello    hello

            hello                             hello

            hello                             hello

            hello     hello     hello    hello


Lists


Examples
Explanations
cards = [“ace”, “king”, “queen”]   
defines a list
cards[0] is “ace” elements are accessed via subscripts
cards[0] = “spot” You can assign to a list
cards.append(“more”) You can append to the end of a list
cards = [“well isn’t this fancy”,”yes”] + cards You can add to the beginning
del cards[3]   delete an element by index number
cards.remove(“queen”)  delete by value using remove

cards.insert(1,”test”) 

insert an element as this position

len(cards) length
max(cards)
max and min
newsomething = cards[:]

a new copy

cards.reverse() 
reverse() and sort()

Can use for statements with lists (in fact you have used this)


for card in cards:    
    print card;


Dictionaries - lists whose indices are numbers and strings


Try hangman (this from http://inventwithpython.com/IYOCGwP_book1.pdf)


File I/O


file = open(“outputFile.txt”,”a”)                              # open for appending

file = open("someAsciiFile.txt","r")                        # open for reading

file = open(“outputFile.txt”,”w”)                             # open for writing


file.close()                                                                   # close the file

text = file.readlines()                                                 # read all lines into a list called text

line = file.readline()                                                   # read next line into a string called line

file.writelines(text)                                                    # write list to file

file.write(line)                                                             # write one line to file


For example:

 

file = open("someAsciiFile.txt","r")

text = file.readlines()

file.close()

 

for line in text:

    print line


 

If your file is huge, use the following instead

 

#!/usr/bin/env python
#
# Program to read and print a file
#
file = open("alice.txt","r")
line = file.readline()

while line:
    print line,
    line = file.readline()
print

file.close()


Adding some error checking:

#!/usr/bin/env python
#
# Program to read and print a file
import sys

try:
    file = open("sample.txt","r")
except IOError:
    print "Could not open file"
    sys.exit()

text = file.readlines()
file.close()

for line in text:
    print line,
print



OOP - see next set of notes