You are on page 1of 37

CodeAcademy Python

Python

Author: Howell
CodeAcademy Python
Introduction
String
String Formatting

Conditions and Flows


If statement
Input and Output

Function
Import Module (Library)

List and Dictionary


List
List Slicing
String Slicing
Sorting (and for loop)
Iterating over a List in a Function
Using List as Two Argument
List of List
Battleship Example

Dictionary
Editing a Dictionary
Dictionary with Multiple Type of Values
Example of Dictionary
Example of Dictionary

Loop
While loop
Multiple List (zip)
For / Else
More Combined Examples

Iterators
Iterators for Dictionaries
List Comprehension
List Slicing Syntax
Function Programming

Introduction to Bitwise Operators


Base 2 Number System
bin() Function
int Function
Shift to the Right/Left
Bitwise Comparison
Example

Class
Base form
Scope
Member Variables
Example
Inheritance
Override
Example of Class
Example of Inheritance
Example of Overriding
Overriding Method

File Input and Output


Open a File
Write to a File
Read from a File
Read Line by Line
Automatically close file (using with and as)
Test whether Closed

Introduction

#Creating a variable
my_variable = 10
my_bool = True
my_float = 1.23

"""Proper indent the code with four spaces


multiple line comment
"""

#Exponential
eggs = 10**2

#Modulo (remainder)
spam = 3 % 2

String
#Escaping character
"""
'There's a snake in my boot!'
This code breaks because Python thinks the apostrophe in 'There's'
ends the string.
We can use the backslash to fix the problem, like this:
'There\'s a snake in my boot!'
"""
'This isn\'t flying, this is falling with style!'

#Access by Index
"""
The string "PYTHON" has six characters,
numbered 0 to 5, as shown below:

+---+---+---+---+---+---+
| P | Y | T | H | O | N |
+---+---+---+---+---+---+
0 1 2 3 4 5

So if you wanted "Y", you could just type


"PYTHON"[1] (always start counting from 0!)
"""
fifth_letter = "MONTY"[4]
print fifth_letter #Print out 'Y'.

#String methond
parrot = "Norwegian Blue"
len(parrot) #Get the length of parrot.
parrot.lower() #De-capitalize all the letters.
parrot.upper() #Capitalize all the letters.
str(3.14) #turns non-strings into strings, useful when combining nu
mber with string.
#e.g. print "The value of pi is around " + str(3.14)

def digit_sum(n):
total = 0
for i in str(n): #Foce n to be a string.
total += int(i) #Force i to be an int.
return total
thing = "spam!"
for l in thing:
print l #Print out every letter perpendicularly.
print l, #Print out every letter on the same line.

#Dote notation
"""
Methods that use dot notation only work with strings.
On the other hand, len() and str() can work on other data types.
"""

String Formatting

"""
Use % operator to combine a string with a variable.
% operator will replace a %s in the string with the string variable
that comes after it.
"""
string_1 = "Camelot"
string_2 = "place"

print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)


#Here string_1 and string are combined.

#Multiple addition
"""
You need the same number of %s terms in a string as the number of v
ariables in parentheses
"""
name = raw_input("What is your name?")
quest = raw_input("What is your quest?")
color = raw_input("What is your favorite color?")

print "Ah, so your name is %s, your quest is %s, " \


"and your favorite color is %s." % (name, quest, color)

Conditions and Flows


#And
True and False

#or
True or False

#not
not 3**4 < 4**3
not not False
"""
Evaluation order: first not, and, or last.
"""

If statement

def greater_less_equal_5(answer):
if answer>5:
return 1
elif answer<5:
return -1
else:
return 0

print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)

Input and Output

print 'Welcome to the Pig Latin Translator!'

# Start coding here!


original = raw_input("Enter a word:")
if original > 0 and original.isalpha() == True: #.isalpha() returns
True if original only contains alphabet letters.
print original
else:
print "empty"

Function
def square(n): #Header, n is a parameter.
"""Returns the square of a number."""
squared = n**2
print "%d squared is %d." % (n, squared)
return squared

# Call the square function on line 9! Make sure to


# include the number 10 between the parentheses.
square(10)

def power(base, exponent):


result = base**exponent
print "%d to the power of %d is %d." % (base, exponent, result)

power(37,4) # 37 and 4 are arguements.

Import Module (Library)


# Ask Python to print sqrt(25) on line 3.
import math #generic import

#Tell Python to import the sqrt() function from math.


print math.sqrt(25)

"""
If we only need to use sqrt, we can import in this way so
we do not have to type math.import over and over again.
math is a module and sqrt() is a function.
"""
from math import sqrt

#Universal import
"""
Import everything from the math module so we do not have to retype
it.
Universal import is generally not good since there might be some co
nflict with its function name and your function name.
"""
from math import *

import math # Imports the math module


everything = dir(math) # Sets everything to a list of things from m
ath
print everything # Prints 'em all!

#Built-in function. (No need to call module.)


min(1,3,4)
max(1,2,3)
abs(1)
print type(42)
print type(4.2)
print type('spam')

List and Dictionary

List
#Declare a list by adding elements to it.
zoo_animals = ["MIFFY","pig", "sloth"];

#Access the elements of a list using index (starting at 0)


print zoo_animals[0] #Print MIFFY

#Assign new value.


zoo_animals [2] = "Miffy little pig"

#Adding element to the BACK


suitcase = [] #Empty list
suitcase.append("sunglasses")
list_length = len(suitcase)

#Remove an element.
backpack = ['xylophone', 'dagger', 'tent', 'bread loaf']
backpack.remove('dagger')


n = [1, 3, 5 1]
n.pop(1) #removes 3 (the item at index 1)
n.remove(1) #remove 1 (find the item and remove it (once))
del(n[1]) #remove 3

List Slicing

#Watch out the index


suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "sho
es"]

# The first and second items (index zero and one)


first = suitcase[0:2]
# Third and fourth items (index two and three)
middle = suitcase[2:4]
# The last two items (index four and five)
last = suitcase[4:6]

duck_index = animals.index("duck") # Use index() to find "duck"


animals.insert(2,"cobra") #Inserting "cobra" at position 2.

String Slicing
animals = "catdogfrog"
#The first three characters of animals
cat = animals[:3]
#The fourth through sixth characters
dog = animals[3:6]
#From the seventh character to the end
frog = animals[6:]

Sorting (and for loop)

start_list = [5, 3, 1, 2, 4]
square_list = []

for number in start_list:


square_list.append(number ** 2)
square_list.sort() #Alphabetical order.

print square_list

Iterating over a List in a Function


#Method 1
for item in list:
print item

#Method 2
for i in range(len(list)):
print list[i]

#Example
n = ["Michael", "Lieberman"]
def join_strings(words):
result = ""

#Method 1
for word in words:
result += word
return result

#Mehod 2
for i in range(len(words)):
result += words[i]
return result

print join_strings(n)

Using List as Two Argument

a = [1, 2, 3]
b = [4, 5, 6]
print a + b #prints [1, 2, 3, 4, 5, 6]

List of List

list_of_lists = [[1,2,3], [4,5,6]]

for lst in list_of_lists:


for item in lst:
print item #print 1 2 3 4 5 6

Battleship Example
#You can hide your battle in the map and the player is going to gue
ss where it is.
board = []
for i in range(0,5):
temp = ["O"] * 5
board.append(temp)
print board #Print a grid with 5 x 5 "O"

#Polishing the map


def print_board(board):
for row in board:
print " ".join(row) #Use " " to separate O's when printing.

#Generating random coordinate.


from random import randint #Random number module.
def random_row(board):
return randint(0,len(board)-1) #randint(low,high)
def random_col(board):
return randint(0,len(board)-1)

guess_row = int(raw_input("Guess Row:"))


guess_col = int(raw_input("Guess Col:"))

print ship_row
print ship_col

if guess_row == ship_row and guess_col == ship_col:


print "Congratulations! You sunk my battleship!"
break
else:
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or gu
ess_col > 4):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
else:
print "You missed my battleship!"
if turn == 3:
print "Game Over"
board[guess_row][guess_col] = "X"
# Print (turn + 1) here!
print_board(board)
CodeAcademy Python
Introduction
String
String Formatting

Conditions and Flows


If statement
Input and Output

Function
Import Module (Library)

List and Dictionary


List
List Slicing
String Slicing
Sorting (and for loop)
Iterating over a List in a Function
Using List as Two Argument
List of List
Battleship Example

Dictionary
Editing a Dictionary
Dictionary with Multiple Type of Values
Example of Dictionary
Example of Dictionary

Loop
While loop
Multiple List (zip)
For / Else
More Combined Examples

Iterators
Iterators for Dictionaries
List Comprehension
List Slicing Syntax
Function Programming

Introduction to Bitwise Operators


Base 2 Number System
bin() Function
int Function
Shift to the Right/Left
Bitwise Comparison
Example

Class
Base form
Scope
Member Variables
Example
Inheritance
Override
Example of Class
Example of Inheritance
Example of Overriding
Overriding Method

File Input and Output


Open a File
Write to a File
Read from a File
Read Line by Line
Automatically close file (using with and as)
Test whether Closed

Dictionary

"""
Dictionary uses key-value pairs to link keys and values.
We can use key to access values.
e.g. Phone books.
"""

residents = {'Miffy' : 104, 'Sloth' : 105, 'Burmese Python' : 106}


#Create a dictionary call residents.

print residents['Miffy'] # Prints Miffy's room number


print residents['Sloth']
print residents['Burmese Python']

Editing a Dictionary
#Add new values
menu = {} #Empty dictionary.
menu["Miffy"] = 520
menu["Miffy little pig"] = 521
menu["Miff"] = 521 #A value can have multiple keys associated with
it.

#Delete and change values.


del residents['Sloth']
residents['Miffy']='Miffy\'s little room'

Dictionary with Multiple Type of Values

inventory = {
'gold' : 500, #Add a coma between each key
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list
to 'pouch' key
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}

# Adding a key 'burlap bag' and assigning a list to it


inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed slot
h']

# Sorting the list found under the key 'pouch'


inventory['pouch'].sort()

inventory['pocket'] = ['seashell', 'strange berry', 'lint']

inventory['backpack'].remove('dagger')

inventory['gold']=[50,550]

for keys in inventory:


print inventory[keys] #Print out all the values.

Example of Dictionary
shopping_list = ["banana", "orange", "apple"]

stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}

prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}

def compute_bill(food): #Find the total of item in food


total = 0
for number in range(0,len(food)):
if stock[food[number]]>0: #Test whether in stock.
total += prices[food[number]]
stock[food[number]]-=1
return total

Example of Dictionary
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}

# Add your function below!


def average(numbers):
total = sum(numbers)
total = float(total)
return total / len(numbers)

def get_average(student): #Get the weighted score of a student.


homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
return homework * 0.1 + quizzes * 0.3 + tests * 0.6

def get_letter_grade(score):
if score >= 90:
return "A"
elif score >=80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"

def get_class_average(students):
results = []
for student in students:
results.append(get_average(student))
return average(results)
my_class = [lloyd, alice, tyler]
print get_class_average(my_class)

for student in my_class:


print get_letter_grade(get_average(student))

Loop

While loop

#While loop
count = 0
while True: #Condition
print count
count += 1 #Index
if count >= 10:
break

#While / Else
import random

print "Lucky Numbers! 3 numbers will be generated."


print "If one of them is a '5', you lose!"

count = 0
while count < 3:
num = random.randint(1, 6)
print num
if num == 5:
print "Sorry, you lose!"
break
count += 1
else:
print "You win!"
#print out index as well.
choices = ['pizza', 'pasta', 'salad', 'nachos']

print 'Your choices are:'


for index, item in enumerate(choices):
print index+1, item #index now starts at 1 (more natural)

Multiple List (zip)

"""
zip creates pairs of elements passed two lists, and will stop at th
e end of the shorter list.
"""
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]

for a, b in zip(list_a, list_b):


# Add your code here!
if b > a:
print b,
else:
print a, #Stops at shorter list.
#Print 3 9 17 15 30.

For / Else

"""
the else statement is executed after the for, but only if the for e
nds normallythat is, not with a break.
"""
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']

print 'You have...'


for f in fruits:
if f == 'tomato':
print 'A tomato is not a fruit!' # (It actually is.)
break
print 'A', f
else:
print 'A fine selection of fruits!'

More Combined Examples


#Guess the word.
score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10}

def scrabble_score(word):
total = 0
for l in word:
temp = l.lower()
total += score[temp]
return total

#Get rid of vowels.


def anti_vowel(text):
temp = []
for l in text:
if l in "aeiouAEIOU":
temp.append("")
else:
temp.append(l)
return "".join(temp)

#Replace the chosen word in text with "*".


def censor(text, word):
index = text.index(word)
l = len(word)
text = str.replace(text, word, '*' * l)
return text

Iterators

Iterators for Dictionaries


my_dict = {
"Howell": "Miffy",
"Slim": "Pig", #Miffy you little pig.
"Smart": "Stupid"
}

print my_dict.items() #It does not print in order.


print my_dict.keys() #It does not print in order.
print my_dict.values() #It does not print in order.

List Comprehension

my_list = range(51) #Print 0 to 50 (inclusive)

#Print 2, 4, 6, ..., 48, 50.


evens_to_50 = [i for i in range(51) if i % 2 == 0]

#Print 6
doubles_by_3 = [x*2 for x in range(1,6) if (x*2) % 3 == 0]

List Slicing Syntax


#List Slicing
#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
l = [i ** 2 for i in range(1, 11)]

#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


print l

#[9, 25, 49, 81]


print l[2:9:2]
#2: start index (inclusive)
#9: end index (inclusive)
#2: stride (choose every other index)

to_five = ['A', 'B', 'C', 'D', 'E']

print to_five[3:] #Start: 3, end: default, stride: default 1


# prints ['D', 'E']

print to_five[:2] #Start: default, end: 2, stride: default 1


# prints ['A', 'B']

print to_five[::2] #Start: default, end: default, stride: 2


# print ['A', 'C', 'E']

my_list = range(1, 11) # List of numbers 1 - 10


print my_list[::2] #1,3, ..., 9, 11
print my_list[::-2] #11, 9, ..., 3, 1 ->reversed order

Function Programming
"""
Anonymous Function
We don't need to give the function a name but it works the same as
a well-defined function.
"""
my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list) #[0, 3, 6, 9, 12, 15]
#fileter(lambda x: (return condition of x), (source))

squares = [x ** 2 for x in range(1,11)] #1, 4, ..., 100


print filter(lambda x: x < 71 and x > 29, squares) #36, 49, 64

threes_and_fives = filter(lambda x: x % 3 == 0 or x % 5 == 0, rang


e(1,16))

Introduction to Bitwise Operators

Base 2 Number System

#In Python, you can write numbers in binary format by starting the
number with 0b.
print 0b1, #1
print 0b10, #2
print 0b11, #3
print 0b100, #4
print 0b101, #5
print 0b110, #6
print 0b111 #7
print "******"
print 0b1 + 0b11 #4
print 0b11 * 0b11 #9

bin() Function
#bin() takes an integer as input and returns the binary representat
ion of that integer in a string.
for i in range(1,6):
print bin(i)

oct() #Number in base 8


hex() #Number in base 16

int Function

#Specify number base, then the number will be converted to base 10.
print int("1",2)
print int("10",2)
print int("111",2)
print int("0b100",2)
print int(bin(5),2)
print int("11001001",2)

Shift to the Right/Left

shift_right = 0b1100
shift_left = 0b1
shift_right = shift_right >> 2
shift_left = shift_left << 2
print bin(shift_right) #0b11
print bin(shift_left) #0b100

Bitwise Comparison
#And operator
"""
The bitwise AND (&) operator compares two numbers on a bit level an
d returns a number where the bits of that number are turned on if t
he corresponding bits of both numbers are 1.

i.e. only 1 & 1 = 1

e.g.
a: 00101010 42
b: 00001111 15
===================
a & b: 00001010 10

(note: here we use & instead of "and")


"""
print bin(0b1110 & 0b101) #0b100

#Or operator
"""
The bitwise OR (|) operator compares two numbers on a bit level and
returns a number where the bits of that number are turned on if eit
her of the corresponding bits of either number are 1.

i.e. only 0 | 0 = 0

e.g.
a: 00101010 42
b: 00001111 15
================
a | b: 00101111 47
"""
print bin(0b1110 | 0b101) #0b1111

#XOR operator
"""
The XOR (^) or exclusive or operator compares two numbers on a bit
level and returns a number where the bits of that number are turned
on if either of the corresponding bits of the two numbers are 1, bu
t not both.

i.e.
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
"""
print bin(0b1110 ^ 0b101) #0b1011

Example

#A function that will check whether the 4th bit from the right is t
urned on (1).
def check_bit4(input):
mask = 0b1000
desired = input & mask
if desired > 0:
return "on"
else:
return "off"

Class

Base form
"""A class called Animal inherits from class object"""
class Animal(object):
pass #An expected expression when class is empty.

"""A class with function"""


class Animal(object):
def __init__(self):
pass

"""
The part that is magic is the fact that self is the first parameter
passed to __init__(). Python will use the first parameter that __in
it__() receives to refer to the object being created; this is why i
t's often called self, since this parameter gives the object being
created its identity.
"""
class Animal(object):
def __init__(self,name):
self.name = name

"""Instantiating object"""
class Animal(object):
def __init__(self,name):
self.name = name

zebra = Animal("Jeffrey")
print zebra.name #Print out 'Jeffery'

"""More parameter"""
class Animal(object):
# For initializing our instance objects
def __init__(self, name, age, is_hungry):
self.name = name
self.age = age
self.is_hungry = is_hungry

# Note that self is only used in the __init__()


# function definition; we don't need to pass it
# to our instance objects.

zebra = Animal("Jeffrey", 2, True)


giraffe = Animal("Bruce", 1, False)
panda = Animal("Chad", 7, True)
print zebra.name, zebra.age, zebra.is_hungry
print giraffe.name, giraffe.age, giraffe.is_hungry
print panda.name, panda.age, panda.is_hungry

Scope

"""The scope of a variable is the context in which it's visible to


the program."""
class Animal(object):
"""Makes cute animals."""
is_alive = True

#A function is called a method


def __init__(self, name, age):
self.name = name
self.age = age

#Make another method


def description(self): #Pass by self
print self.name
print self.age

Member Variables
class Animal(object):
"""Makes cute animals."""
is_alive = True
health = "good"

#A function is called a method


def __init__(self, name, age):
self.name = name
self.age = age

def description(self):
print self.name
print self.age

hippo = Animal("Howell", 16)


hippo.description
sloth = Animal("Miffy", 12)
ocelot = Animal("Pig", 8)
print hippo.health
print sloth.health
print ocelot.health

Example
class ShoppingCart(object):
"""Creates shopping cart objects
for users of our fine website."""
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name

def add_item(self, product, price):


"""Add product to the cart."""
if not product in self.items_in_cart:
self.items_in_cart[product] = price
print product + " added."
else:
print product + " is already in the cart."

def remove_item(self, product):


"""Remove product from the cart."""
if product in self.items_in_cart:
del self.items_in_cart[product]
print product + " removed."
else:
print product + " is not in the cart."

my_cart = ShoppingCart("Howell")
my_cart.add_item("bra", 10000)

Inheritance

class Shape(object): #Base class.


def __init__(self, number_of_sides):
self.number_of_sides = number_of_sides

"""Triangle is the derived class and


shape is the base class"""
class Triangle(Shape): #Inherited class
def __init__(self,side1,side2,side3):
self.side1 = side1
self.side2 = side2
self.side3 = side3

Override
class Employee(object):
"""Models real-life employees!"""
def __init__(self, employee_name):
self.employee_name = employee_name

def calculate_wage(self, hours):


self.hours = hours
return hours * 20.00

class PartTimeEmployee(Employee):
#PartTimeEmployee.calculate_wage overrides
#Employee.calculate_wage
def calculate_wage(self,hours):
self.hours = hours
return hours * 12.00

#We will use super here to show overriding.


def full_time_wage(self,hours):
return super(PartTimeEmployee, self).calculate_wage(hours)

milton = PartTimeEmployee("miffy")
print milton.full_time_wage(10) #Still $20/h

Example of Class
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg

def display_car(self):
print "This is a %s %s with %s MPG." % (self.color,self.mod
el,str(self.mpg))

def drive_car(self):
self.condition = "used"

my_car = Car("DeLorean", "silver", 88)


print my_car.condition #"new"
print my_car.drive_car() #After driving the car, condition becomes
"used"
print my_car.condition #"used"

Example of Inheritance
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg

#Create a subclass.
class ElectricCar(Car):
def __init__(self, battery_type, model, color, mpg):
self.battery_type = battery_type
Car.__init__(self, model, color, mpg)

#Aother way to create the same subclass


class ElectricCar(Car):
def __init__(self, model, color, mpg, battery_type):
self.model = model
self.color = color
self.mpg = mpg
self.battery_type=battery_type

my_car = ElectricCar("Volkswagen", "red", 30, "molten salt")

Example of Overriding
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg

def display_car(self):
print "This is a %s %s with %s MPG." % (self.color,self.mod
el,str(self.mpg))

def drive_car(self):
self.condition = "used"

class ElectricCar(Car):
def __init__(self,model, color, mpg, battery_type):
self.model = model
self.color = color
self.mpg = mpg
self.battery_type=battery_type

def drive_car(self):
self.condition = "like new"

my_car = ElectricCar("Volkswagen", "red", 30, "molten salt")

print my_car.condition #"new"


my_car.drive_car() #Call the drive_car() method
print my_car.condition #"like new"

Overriding Method
#The use of __repr__()
class Point3D(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z

def __repr__(self):
return "(%d, %d, %d)" % (self.x, self.y, self.z)

my_point = Point3D(1, 2, 3)
print my_point

File Input and Output

Open a File

my_file = open("output.txt", "r+") #Allow read and write


my_file = open("output.txt", "w") #Allow write
my_file = open("output.txt", "r") #Allow read only

Write to a File

my_list = [i**2 for i in range(1,11)]

my_file = open("output.txt", "r+")

#use .write() to write to the file.


#. write() only accept string

for i in my_list:
temp = str(i) + "\n"
my_file.write(temp)

#Must close when done.


my_file.close()

Read from a File


#Read from a file
my_file = open("output.txt", "r")
print my_file.read()
my_file.close()

Read Line by Line

#Use .readline() to read line by line instead of read the eitire fi


le at once.
my_file = open("text.txt","r")
print my_file.readline()
print my_file.readline()
print my_file.readline()
my_file.close()

The reason why we need to close our file once we are done with it:

During the I/O process, data is buffered: this means that it is held in a temporary location
before being written to the file.

Python doesnt flush the bufferthat is, write data to the fileuntil its sure youre done
writing. One way to do this is to close the file. If you write to a file without closing, the data
wont make it to the target file.

Automatically close file (using with and as)

#Open "test.txt" as my_file


with open("text.txt", "w") as my_file:
my_file.write("Success!") #Print out 'success'
#my_file will be automatically closed after we are done.

Test whether Closed


"""Python file objects have a closed attribute which is True when t
he file is closed and False otherwise."""
with open('test.tst', 'w') as my_file:
my_file.write('success')
if my_file.closed== False:
my_file.close()
print my_file.closed

The end of Python Intro.

You might also like