I210 review
Fall 2011, IUB
Python is• High-level programming
– High-level versus machine language
• Interpreted Language– Interpreted versus compiled
2
Variables• Variable: Represents a value; provides way
to get at information in computer memory• Assignment statement: Assigns a value to
a variable; creates variable if necessary• Rules for legal variable names
– Can contain only numbers, letters, and underscores
– Can’t start with a number– Can’t be a keyword (del, elif, else, except, for ,
from, global, if, import, in, is, not, or, print, return, try, while, with)
3
Data Types• Data type: sequences (containers)
– Strings (a sequence of letters)– Tuples (a sequence of elements of any type;
immutable)– Lists (a sequence of elements of any type; mutable)– Dictionary is NOT a sequence
• How to access the elements in a sequence– Sequential access (using for and while loops)– Indexing & Slicing
• Removing and adding elements• Important sequence operators and functions,
len([1, 2, 3]), ”a" in "abc", [1, 2, 3].index(1)4
Mathematical Operators
Indexing & Slicing Sequences
inventory = ["sword", "armor", "shield", "healing potion"]
inventory[0] ?inventory[0][1]?inventory[0:2]?
6
List Methods
languages = ["Python", "C++", "Java", "HTML"]
• languages.append("FORTRAN")• languages.remove("C++")• languages.sort()• languages.count"C++")• languages.index("Python")• languages.insert(0, "PHP")• languages.pop ()
Using the Right Types• Python does not need to specify the type of a
variable in advance (by contrast, C does)Python: cost = 10
C: int cost = 10;
• Important to know which data types are available• Equally important to know how to work with them• If not, might end up with program that produces
unintended results• Converting values: e.g., int(“3”) = 3
8
Lists versus Tuplesinvent_list = ["sword", "armor", "shield", "healing potion"]invent_tuple = ("sword", "armor", "shield", "healing potion")
invent_list[0] = "money" is OK!!invent_tuple[0] = "money" ERROR
• Lists are mutable (we can dynamically change the individual elements!); but tuples are immutable
• Strings are immutableword = "sword”
word[0] = "S" ERRORword = "Sword" is OK!!
Using Dictionaries
• Dictionary: A mutable collection of key-value pairs
geek = {"404" : "clueless.", "Uninstalled" : "being fired."}
• Unlike tuples and lists, dictionaries don’t organize data into sequences, but pairs
• Look up a key to get a value
geek["404"]10
Branching Structures
• Branches based on a condition/conditions– if– if-else– if-elif-else
• Condition: Expression that is True or False• Often create conditions by comparing values
Treating values as conditions: Any empty (None) or zero value is False
• Compound conditions (logical operators)– and, or, not
11
Branching Structures
12
Branches based on a condition/conditions
A block of code
Using Indentation to Create BlocksCorrect:if password == "secret":
print "Access Granted"else:
print "Access Denied”
Incorrect:if password == "secret":
print "Access Granted” else:
print "Access Denied"
13
Loop Structure
• Need to know when and how to use for and while loops correctly– for loops: iterate over the elements in a
sequence– while loops: repeat a block of code as long
as a condition is
• insertion_sort.py
14
The while Loop
while condition:<block>
while response != "Because.":response = raw_input("Why? ”)
Repetition based on a condition– Allows you to repeat section of code as long as some condition
is True – Like if statement, in that it tests a condition and executes
associated block if condition True– But, after block, repeats condition test; if condition still True,
repeats block– Continues process until condition tests False
15
The continue & break Statementswhile True:
count += 1# end loop if count is greater than 10if count > 10:
break# skip 5if count == 5:
continueprint count
• continue jumps to top of loop to check condition
• break causes a loop to end immediately
16
Using for Loops
• for loop – Like while loop, repeats a loop body– Unlike while loop, doesn’t repeat based on
condition– Repeats loop body for each element in a
sequence– Ends when it reaches end of the sequence– e.g., go through sequence of game titles and
print each
17
Counting Forward, By Fives, and Backwards
# counting forwardfor i in range(10):
print i,
# counting by fivesfor i in range(0, 50, 5):
print i,
# counting backwardsfor i in range(10, 0, -1):
print i,
18
Functions
• How to write functions• How to receive and return values
– Not all functions take arguments, and not all functions return values!!
• Understand local and global variables
• And don’t forget to call functionsdef my_func():
print "this function does nothing"my_func()
19
Working with Files• Open a file ("r", "w")• Read/write
– Read from text files; readline(), readlines()– Write to text files (permanent storage); write(), writelines()
• Close the filetext_file = open("read_it.txt", "r”)line1 = text_file.readline()text_file.close()
• Loop through a filetext_file = open("read_it.txt", "r")for line in text_file: print line
Types of Errors
• Syntax errors– “Computer doesn’t understand what I wrote, because I
made a typo”• Logical Errors
– Program does not perform correctly– Debugging
• Runtime Error– The program saves and begins to execute, then
crashes, usually after receiving input– try-except statements
Handling Exceptions
try: num = float(raw_input("\nEnter a number: "))except(ValueError): print "That was not a number!"else: print "You entered the number", num
• Can add single else clause after all except clauses • else block executes only if no exception is raised• num printed only if assignment statement in the try
block raises no exception
22
A Sample Question
• Write a function that accepts a filename and reads in the comma-separated numbers from the text file. The function saves the numbers in a list, calculates and displays the average of the numbers, and return the list of numbers.
• Please work out the practice midterm
23