Review material
Download
Report
Transcript Review material
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 Tuples
invent_list = ["sword", "armor", "shield",
"healing potion"]
invent_tuple = ("sword", "armor", "shield",
"healing potion")
invent_list[0] = "money"
invent_tuple[0] = "money"
is OK!!
ERROR
• Lists are mutable (we can dynamically change the
individual elements!); but tuples are immutable
• Strings are immutable
word = "sword”
word[0] = "S" ERROR
word = "Sword" is OK!!
Using Dictionaries
• Dictionary: A mutable collection of keyvalue 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
Branches based on a condition/conditions
A block of code
12
Using Indentation to Create Blocks
Correct:
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
Statements
while True:
count += 1
# end loop if count is greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
print count
jumps to top of loop to check
condition
break causes a loop to end immediately
• continue
•
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 forward
for i in range(10):
print i,
# counting by fives
for i in range(0, 50, 5):
print i,
# counting backwards
for 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 functions
def 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 file
text_file = open("read_it.txt", "r”)
line1 = text_file.readline()
text_file.close()
• Loop through a file
text_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