Download Introduction to Programming

Document related concepts
no text concepts found
Transcript
Introduction to Programming
Introduction – What is this course about?
This course is an introduction to art and craft of programming using the python programming
language. We will assume no background in programming at all, but by the end of the
semester, you should understand what programming is all about and should be quite
proficient at composing interesting programs in Python.
Programming
This course is very “hands-on” because the only way to learn to program is by programming. We
will frequently be working out problems together during the lecture, and there will generally be
at least one program assigned for homework each week and at times … each class. Some will be
quite straight forward, but some of the others, especially as the course progresses, …  should
be more fun …… Very important: please make sure that you set aside sufficient time to
work on the programs.
You should first try to work the programs out by yourself. Sometimes this will be easy,
sometimes a bit more difficult. You may discuss the projects with your classmates, and as the
problems get more challenging that is a good idea, but the assignments you hand in must be your
own work. Besides the college policy on plagiarism (and the academic consequences thereof,
see: http://cs.nyu.edu/webapps/content/academic/undergrad/academic_integrity), what you gain from
the course is directly proportional to what you put in.
Getting Help
Do not let things get out of hand! For many of you, the material in this course will be
new and require a different way of thinking and, some of you, might need more time to “get it”
than others. That is perfectly natural. But, please, do not be shy about asking for help when and
if you need it. You can see me during my office hours (posted on the web site), write to the TA,
and there are very knowledgeable tutors available in the computer labs. Please make use of these
resources.
Topical Syllabus
Why a “topical syllabus”?
Each group of students is unique and so, in different classes, we need to spend more or less time
on specific topics. We will cover the topics below, more or less in the order indicated. I will be
letting you know in class what to prepare for the next few classes.








Introduction to computers and computing
The Python environment
Values and data types
Input and output
Hello World!
Variables, and assignment
Control Structures (if, if/else, while, for)
Functions and modules
1



Sequences, lists, strings, sets, tuples
Working with text
additional material in-between and after the above, as time permits
Requirements
Exams
Two midterms (20% each) and a final (35%).
Projects
Twenty five percent (25 % ) of the final grade.
How to hand in the homework.
Email the file to the TA at the email address on the web page. Given the size of the class we will
be enforcing the homework deadlines strictly unless otherwise announced.
Texts
Listed on the class website.
http://cs.nyu.edu/courses/spring14/CSCI-UA.0002-002/index.html
How to use these notes?
These notes are not a substitute for the text book. After a fairly detailed introduction, the notes
will provide an outline of important ideas, and a place to work out the problems that we tackle in
class. The contain most (but not necessarily all) of the material that we cover in the lecture.
There will be lots of space for you to write answers to question that come up in class. Use these
notes as your notebook to take class notes.
Important: You are responsible for material that we cover in class but are not in the notes. If
you miss any classes, please make sure that you are current.
2
Most of the course will deal with programming in Python, but first a general
introduction to computers and computing.
What is a computer system? A “system” that does “computation.”
So … what is required of such a system?
Consider the following simple problem. We want this clever fellow to solve the problem on the
paper.
What capabilities are required to solve it? Where are they “located?”
O
3
+
3
5
Where are the equivalent “capabilities” on a computer?
Front view:
Rear view:
4
Let’s look at the hardware of a typical computer system. It consists of:
1. input devices:
2. output devices:
3. memory: (“short term” and “long term”)
a. primary memory = RAM = Random Access Memory (for short term storage)
b. Hard drives, diskettes, CD ROM = Compact Disk Read Only Memory, USB (Universal
Serial Bus) flash drives, DVD = Digital Versatile Disc or Digital Video Disc
Aside: Binary numbers. Numbers expressed using only 1
and 0. –
Computers represent information in binary. Why?
5
Representing integers in binary
We usually write numbers in decimal notation. That means that each position represents a power
of 10.
For example: 135 = one hundred and thirty five is "really"
135
=
1*102 + 3*101 + 5*100
"* " in this context means multiply.
We can also express numbers in binary notation.
Huh?
Binary means that the "base" of the representation is 2 instead of 10. So here we are multiplying
by powers of 2 rather than powers of 10.
Also whereas in the decimal number system there are 10 "digits" to choose from for each
position, the numbers from 1 to 9, in binary there are only 2: 1 or 0.
Ex:
1101 = 1* 23 + 1*22 + 0*21 + 1*20
What number is 11012 ?
Ex: Write out the binary numbers from 0 -7, using three "bits" (binary integers)
1
2
3
4
5
6
7
6
We can convert from decimal to binary notation and vice versa.
How? Here is an easy way.
Decimal to binary:
27
64
86
Binary to decimal
110
11100011
7
The following units are used to measure various “capacities” of storage devices.
Bit (b)
Byte (B)
KB
MB
GB
TB
PB
The anatomy of a floppy disk – ever see one?? Similar in some ways to a hard drive.
What happens when we format a diskette or the hard drive? (Remember formatting
is a “destructive” operation)
….. but sometimes, not destructive enough. When? …
The anatomy of a hard drive.
8
c. ROM = Read Only Memory
4. System unit: (Arithmetic Ability and Control)
CPU = Central Processing Unit
ALU = Arithmetic and Logic Unit
Registers, etc. ....
Control unit
All connected by the BUS. In the diagram below the BUS is represented by the double
arrows.
9
What about a modem? Does it represent …
Input?
Output?
Communication?
10
Modem = MO+ DEM
MO=Modulate / DEM=DEModulate
AM radio = Amplitude Modulation
FM radio = Frequency Modulation
So the modem Modulates the carrier signal when it sends it out:

it “adds” the binary information onto the analog carrier signal
and
DeModulates the signal when it is received

It “subtracts out” the carrier signal when input is received and is left with the “bits”, i.e.
binary digits (information) that hitched a ride on the carrier wave.
Basic idea:
The information is represented in the change from the underlying “carrier.” When we read words
on a printed page, our brain “subtracts out” the blank “carrier” (white page) and the information
is in the characters that changed the white background.
11
Python
In this course we will learn to program in the Python programming language. You can read
something about its history in the textbook and on the web.
Question: There are there many programming languages: Python, C, C++, Java, Ruby, COBOL
(still), Fortran (still too) …..Why so many?
Answer:
Download Python and install it on your laptop.
Python can be downloaded for free from the official Python web site:
http://python.org/
We will be using Python 3.3.3. Make sure you download and install the correct version
(Windows/Mac) and the 32 or 64 bit version. Help is available at the NYU computer labs.
IDLE – Integrated Development Environment
When Python installs you will be able to access its functionality through the IDLE interface.
12
We will be accessing Python in three different ways.
1. The interactive shell. This is available when we bring up IDLE. We will make limited use of
this, mostly to experiment with various Python constructs and to test out ideas.
2. Python programs. This will be our main focus. A program is a file containing a sequence of
statements in the Python language. We will create these files using IDLE and then “run” the file
which will execute the statements in the program.
3. A Python Emulator. This website will allow us to “step through a python program and “see”
what is happening in the memory after each instruction is executed. We will use this in class and
it is an excellent tool when you are debugging (eliminating errors) your programs. It is available
here: http://pythontutor.com/
And now …….
13
We first examine some Python constructs by using the interactive shell. Then
we go on to programming.
Python is a programming language – i.e. a “language” that is used to program computers.
Just like a natural language, it contains


nouns and
verbs.
The nouns name “things” and the “verbs” tell what to do with the nouns
Throw ball!  verb noun
Eat apple!
 verb noun
Read book.  verb noun
Notice: different verbs for different nouns. You don’t eat a book or read an apple. It will be
similar in Python.
Data Types – A Classification of Python’s Nouns
More precisely, a data type is thought of as the combination of the nouns and the verbs that they
respond to.
The basic data types in Python are:




Integers
Floats
Strings
Booleans
.
There will be more later on.
The data types denote sets of the different types of Pythons nouns. The individual elements of
the set, the constants, are the nouns. For example, One of Python’s data types is “integer”, i.e.
all of the whole numbers. Each particular number is like a noun. It’s like in a natural language
there is the class of “nouns” (the data type) and individual nouns in that class.
Since one of the main things that we want to do with Python is mathematical computations,
Python provides two kinds of arithmetic “nouns”, i.e. numbers, the integers and floats, and
operations on them.
When we perform operations on the data we are generation something called an “expression.”
Simply put an expression is something that Python can evaluate, that is we can perform the
operations and get a value. We will see examples as we look at the specific data types.
14
The first data type:
Integer: a whole number, positive, negative or 0. Integers in Python can be arbitrarily long and
are written without commas. Other programming languages generally limit the size of integers.
0
56
-897
345678987654323456787665543093764830036455489302002
Operations on integers:
Python provides the standard mathematical operations (we call them operators) on integers,
with a twist or two.
1. Addition  123 + 56
Notice that adding two integers always produces another integer.
2. Subtraction 123 – 56
Notice that subtracting two integers always produces another integer.
3. Multiplication  123*56
Notice that multiplying two integers always produces another integer.
4. Division There are two division operations available for integers: “/” and “//”.
The “/” operator.
“/” will perform “regular” division so 123/56  2.19, i.e. produces a “floating point” number,
(a number with a decimal point) which we will see next.
Even when the numbers divide exactly, the result of “/” will always be a float and contain a
decimal point.
2/1  2.0
The “//” operator.
123//56  2 Notice that the decimal point and all digits to its right are gone! They have been
“truncated.” Its as if Python took the 2.19 above and “chopped off” the decimal point and
everything to its right.
This “//” operation on integers will always produce an integer result.
15
5. “%” the remainder function, called mod. If a and b are integers then a%b returns
(evaluates to) the remainder of a divided by b.
For example:
6. Exponentiation: **
For example: 5**3=125
Operator Precedence (from the word precede)
What is that?
How do we evaluate expressions that contain many operations?
In order of the operator precedence.
16
The order in the table above is from lowest to highest precedence.
For example:
Important: Just like in algebra, we can modify the order of evaluation by using
parenthesis.
17
The second data type:
Float: A floating point number is one that contains a decimal point. We saw an example of this
above with the “/” operation on integers. There is an important technical difference between
integers and floats. As we saw integers can be arbitrarily long (subject to the limitations of your
particular computer hardware) and operations that yield integers are always exact. This is not the
case with floats. Unlike integers, floats have maximum and minimum sizes.
max=1.7976931348623157e+308
min=2.2250738585072014e-308
If any operation yields a float value larger than max, we have an overflow condition. Likewise,
if it yields a value smaller than min, we have an underflow condition, and the values obtained
are incorrect.
Additionally, because of how floats are represented in the computer, many values can only be
approximated. Many floats are only approximate, 1/3 = 0.3333333333333333.
Operations on floats:
Like it does for the integers, Python provides the basic arithmetic operations that you would
expect.
Python even defines the
mod
function for floats as the
following
examples illustrate.
Notice that operations involving two floats produce a float result. This is true even if one of the
operand is an integer (123.0 * 2  is a float even though 2 is an integer.
The next two data types are not arithmetic.
18
The third data type:
String: A string is a sequence of one or more characters. An individual character is also a string
in Python. We denote a string by surrounding the character sequence by matching pairs of
quotes. The quotes are: (1) ‘, (2)”, (3) three of the first two – ‘’’ or “””. Here are some examples:
Operations on strings:
Python provides a very rich set of string operations and functions. We will see them later on. For
now we look at probably the most important one: “+” called concatenation.
What about 3*’Hello’? Can we “multiply strings?
How come??????
19
The forth data type:
Boolean: This data type has two values: True and False (spelled just as you see them – first
letter caps and others lower case).
In addition … certain operations yield Boolean values, specifically, comparison operations
on arithmetic and string expressions yield comparison expressions.
Arithmetic expressions are expressions that yield numbers. String expressions yield strings
(‘abc’+’def’  ‘abcdef’). We have seen these above.
What are comparison operations?
Comparison operations
Python provides the following comparison operations:
>
<
>=
<=
==
!=
greater than
less than
greater than or equal to
less than or equal to
equal to
not equal to
When we use these to compare the values of arithmetic expressions, we get a Boolean value.
We can also use these comparison operations on strings. The value of the comparison depends of
the lexicographic ordering (dictionary ordering – which string appears earlier or later in a
dictionary) of the strings.
20
We can chain the comparison operations in a standard “mathematical” way and write things
like:
x<=y<z where x,y,z are appropriate values.
Comparison expressions may be combined using Boolean operations:
and
or
not
The operator not yields True if its argument is false, False otherwise.
The expression x and y first evaluates x; if x is false,
otherwise, y is evaluated and the resulting value is returned.
its
value
is
returned;
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is
evaluated and the resulting value is returned.
21
Look at this:
What is going on? How can we multiply (7>5) which evaluates to True by a numbe abd get a
number? Same question with (7<5).
Answer:
There are four more comparison operations provided by Python:
is
is not
in
not in
We will be using these later when we work with sequences and collections of various sorts.
Conversion between data types
Python provides a number of functions that let you convert between different data types:
float()
int()
str()
The function type(x) returns the “type’, i.e. the kind of object x is.
22
Output
How do we get Python to output information?
We have just seen the basic “nouns” (=data types) and some operations on them, i.e. item 3
below. We see that Python can get the computer to perform arithmetic and symbolic (e.g. string)
manipulation.
Recall:
1. Input
2. Output
3. Memory
4. Arithmetic – symbolic manipulation and evaluation
5. Control
What about output?
1. Input
2. Output
3. Memory
4. Arithmetic – symbolic manipulation and evaluation
5. Control
23
Question: Where can we output to?
For now, all of our output will be sent to the monitor (=screen).
How? We use the print
statement.
print(‘Hello world’)
Here is the syntax of the print statement.
As soon as I started to type the print command Python shows me the syntax. Here is how to read
it.
First of all, print is a “function.” A function has



A name (here – print is the function name)
Followed by parenthesis
And zero or more “arguments “passed in”. If there is more than one argument, they are
separated from each other by a comma.
24
What do the arguments mean/control?
value
sep
end
file
flush
What is a default value:
Now:
Print the values 1, 2, 3 all on one line
25
Print the values 1,2 3 one per line. Do this in two ways.
More examples using print:
26
Programming
Plan for the rest of the semester:
We will be introducing various new elements of Python and using them to solve increasingly
interesting and complex problems.
We saw earlier that computers can (1) input, (2) output, (3) memory (store information), (4) do
arithmetic and symbolic processing, and (5) control.
Implication: a program is a sequence of statements (commands and functions) that
“speak” to one or more of those capabilities.
The examples we have seen till now used the command shell mode. We enter one statement
or expression, hit <enter> and Python evaluates it for us immediately.
We will start to write programs and get Python to execute (run) them for us.
So … we (1) write then (2) execute.
When we write a program, we



create a text file
enter a sequence of statements
when done, we save the file with a .py extension.
We do this with IDLE.
27
Example: “Hello World” is traditionally the first program everyone writes.
How do we do it?
Answer:
1. Create a new file and type the print command that we saw before.
Pressing F5 will RUN the program.
Type the file name that you want to call the program and Save.
As soon as you Save, the program will run and the result will appear in the interactive shell.
28
Congratulations! You just wrote your first program!
Using comments in Python
You must admit that this one was pretty simple. Not all programs are that straightforward. As
programs get more complex it is often helpful to annotate the various parts of the program so that
someone reading it (even you) can figure out what is happening. We do this using
“comments”, which are indicated in Python by the hash symbol “#”.
They can be of two forms:
They can either be on a line of their own:
or at the end of a program statement:
In either case, the Python interpreter ignores the comment. That is the comment doesn’t
“execute” the comment. It is just there to help the reader of the program understand what is
going on in the code. This implies that we shouldn’t comment on things that are obvious like:
29
New topic: We won’t get anywhere interesting without …..
Variables
Variables allow us to associate a name with a value so that we can use it later on.
Some examples:
x=5
y=10
z=x+y
These are examples of assignment
statements. They have the form:
variable name = expression
Python evaluates the expression on the right of the = and associates the value
obtained with the name on the left.
So in this program:
x=1
y=2
z=x+y
print(x,y,z)
What will this look like in memory?
Trace the program as it runs.
30
Aside: Using the Python emulator. It will allow us to step through a program and see what
happens in the memory as each step is executed.
The emulator may be reached at: http://pythontutor.com/ or from the lecture web page.
The Python emulator will be very helpful in debugging.
What is debugging?
Answer:
31
When we run it we get the following:
Notice how the variables x, y, and z point to their respective values.
Python has three other forms of assignment.
1. Extended assignment.
x=y=z=5
2. Assignment to tuples (also called “unpacking”).
x,y,z=1,2,3
32
3. Augmented assignment statement.
The Python documentation puts it like this:
Augmented assignment is the combination, in a single statement, of a binary operation and
an assignment statement:
For example:
Instead of writing
x=x+1
we can write
x+=1
where both accomplish the same thing, viz. increment x by one. More generally we have
x+= expression
which increments x by the value of the expression.
We also have the following augmented assignment operators:
+=
-=
*=
/=
//=
%=
**=
Which do, analogous to +=, what you would expect.
33
Input
How do we get input from the keyboard to use in our program?
Question:
What will the following program print?
print('Hello')
print('My name is <put your name here>') #insert your name
Problem:
Rewrite the above program using only one print statement
Write a program to ask a “user” to type their name. Then have your program greet them.
Now what??? Write a program to generate the following output. Of course, the entered name
should appear instead of “Jerry” (unless you entered “Jerry” …  )
34
Answer:
What is going on in the computer to make your program execute correctly?
Problem:
Modify the above program so that the “!” follows the name without an intervening blank.
Answer
35
Problem:
Write a program to prompt the user for two numbers. Your program will then print the
sum.
Answer:
Problem:
Modify your answer to the above problem so that we get the following:
36
Answer:
Problem:
Write a program to ask the user their age in years. Your program should calculate and print their
age in seconds.
Answer:
Problem:
Write a program that asks the user to enter a temperature in Fahrenheit. Your program should
calculate and print the temperature in Centigrade.
37
We can translate between Fahrenheit and Celsius according to the following formulas:
°C x 9/5 + 32 = °F
(°F - 32) x 5/9 = °C
Problem:
Given a temperature in Centigrade, write the assignment statement to calculate the temperature
in Fahrenheit. Now, do it the other way, i.e. go from Fahrenheit to Celsius.
Problem – Rounding a number:
What does it mean to round a number? Say x is a floating point number (i.e., contains a decimal
point). If its fractional part is .5 or greater then we “round” x to the next highest integer. But if
the fractional part is less than .5, we “round down” to x. So, rounding 34.56 35 and 34.48
34. Notice that when we round a float, we get an int.
Write an assignment statement to convert a floating point number x, to its rounded value y.
Do this in two ways: (1) without using the built-in “round” function, and (2) once with. Here is
how the Python documentation describes the round function.
round(x[,
n])
Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it
defaults to zero.
Note: The behavior of round() for floats can be surprising: for example, round(2.675, 2)
gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most
decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues
and Limitations for more information.
Answer:
38
Problem:
Write a program that asks the user to enter an integer. Your program should “echo” the input and
print True if the number is even and False if the number is odd.
Problem:
Write a program that asks the user to enter an integer. Your program should “echo” the input and
print EVEN if the number is even and ODD if the number is odd.
39
Problem:
Write a program that asks the user to enter two integers. Your program should:




“Store” the values entered in variables a and b.
“Print a and b.
“Swap” the values in a and b, so that what was in a is now in b and vice versa.
Print a and b. At this point the values should be the reverse of what you printed above.
Answer:
Will this one work?
How about this?
Note: Python allows a more direct way to do this using “unpacking.” Here is how:
How come this works?
40
Problem:
Look at the following:
Write a program that will calculate a worker’s pay given the number of hours worked and the
rate per hour. Both values could be floats, for example if someone worked 35.5 hours at a rate of
$35.75 an hour. Work through the example above.
41
The Format function
This function takes two arguments:


The value that you want printed
The specification of the format to use – for example “field width”, number of digits after
the decimal point, etc.
The syntax is:
format(value to be printed, format specification)
Here is the Python documentation description:
format(value[,
format_spec])
Convert a value to a “formatted” representation, as controlled by format_spec. The
interpretation of format_spec will depend on the type of the value argument, however
there is a standard formatting syntax that is used by most built-in types: Format
Specification Mini-Language.
What in the world does this mean???
We will look at some of the most common ones.
Examples
Formatting floating point numbers:
42
What does the “+” specify?
Formatting integers:
Formatting strings:
43
Problem:
Let’s modify the payment problem above so that we now get the following:
Answer:
New topic
Recall:
1.
2.
3.
4.
5.
Input
Output
Memory
Arithmetic – symbolic manipulation and evaluation
Control
We have seen examples of 1 – 4.
What about …
1.
2.
3.
4.
Input
Output
Memory
Arithmetic – symbolic manipulation and evaluation
5. Control
We have seen a simple example of control. Python simply executes one statement after another
from the first statement of the program to the last. However, sometimes we want to execute
statements conditionally.
44
To do this we use the
if statement
There are three forms. Here is the first.
Example.
When the above program is run (twice) we get:
The syntax (form) of the if statement is:
if <Boolean expression> :
one or more statements (called a code block)
According to the Python documentation, a code block:
A block is a piece of Python program text that is executed as a unit.
The semantics (meaning or interpretation) is:
1. Evaluate the Boolean expression.
2. If its value is True then execute the indented code block, and then continue on with the
statement after the if.
3. If its value is False then simply skip the indented code block and continue with the
statement after the if.
45
Problem:
Write a program that inputs a number and determine if the number is even or odd.
Do this in two ways. (1) Using two if statements. (2) Using only one if ststement and no “fancy”
Boolean expressions.
Answer:
46
Problem:
Write a program that asks for a number, 1, 2, or 3.




If a 1 is entered print the color is red!
If a 2 is entered print the color is green!
If a 3 is entered print the color is blue!
If the number entered is none of those, print ERROR!
Answer
47
Problem:





If n is in the range 1-10, print the color is red!
If n is in the range 1-10, print the color is red!
If n is in the range 11-20, print the color is blue!
If n is in the range 21-30, print the color is green!
If the number entered is none of those, print ERROR!
Answer:
if statement – second form
Example.
The syntax (form) of this if statement is:
if <Boolean expression> :
one or more statements (called a code block)
else:
one or more statements (called a code block)
The semantics (meaning or interpretation) is:
1. Evaluate the Boolean expression.
2. If its value is True then execute the indented code block, and then continue on with the
statement after the if.
3. If its value is False then execute the indented code block statement after the else.
Note: The indentation is important in Python. If the blocks in the “if statement” were not
indented to the right of the “if”, Python would call you out on a syntax error.
How much to indent? Python doesn’t care, but the accepted style in the “community” is four
spaces.
48
Problem:
Write a program that inputs two different integers and prints out the larger of the two.
Answer:
Problem:
Write a program that inputs three different integers and prints out the largest of the three.
Answer:
49
Problem:
Write a program that inputs five different integers and prints out the largest of the five.
Answer:
Problem:
Re-write the following if statement so that it is syntactically correct; then figure out what will be
printed. Test your answer by running the reformatted code.
x=9
y=8
z=7
if x > 9: if y > 8: print ("x > 9 and y > 8") else: if z >= 7: print("x <= 9 and z >= 7") else: print("x <= 9 and z < 7")
In many programming languages the general rule regarding” nested” if statements (an if in
the block of another if) is that the “else” goes with the closest “if” that has no “else.”
Answer:
50
if statement – third form
The syntax (form) of this if statement is:
if <Boolean expression> :
one or more statements (called a code block)
elif <Boolean expression> :
one or more statements (called a code block)
elif <Boolean expression> :
one or more statements (called a code block)
.
.
.
else:
one or more statements (called a code block)
Note: The final “else” is optional.
Question: How many “elif”s do you need?
Answer: As many as you need for the problem that you are solving.
51
The semantics (meaning or interpretation) is:
1. Starting at the first if, find the first Boolean expression that evaluated to True.
2. If one is found, execute the block of statement associated with that if, then exit the whole
“if construct” and continue the program with the statement following it.
3. If no Boolean expression evaluates to True
a. If there is an “else clause”, evaluate it and execute the block of statement
associated with it. Then continue the program with the statement following the
else cause.
b. If there is no “else clause”, then exit the whole “if construct” and continue the
program with the statement following it.
Problem:
Write a program using “if – elif” that converts a numerical score to a letter grade according to the
following scheme:





If the score is 90 or above, the grade is A.
If the score is between 80 and 90 the grade is B.
If the score is between 70 and 80 the grade is C.
If the score is between 60 and 70 the grade is D.
If the score is less than 60, the grade is F.
In the above, between x and y means starting with x and less than y.
The program prints the score and the associated letter grade.
If the score entered is not in any of the above ranges, the program prints the score and the
message “Score out of Range!”.
Answer:
52
Problem:
We will say that a number is a palindrome if it reads the same forwards and backwards. So:



1221 is a palindrome
6556 is a palindrome
1234 is not a palindrome
Write a program that inputs a four digit integer and determines if the number is a palindrome or
not. Your program should reject (politely) any input not in the appropriate range.
Answer:
53
Problem:
Write a program that inputs a three digit integer n (no zero in the units position) and returns the
digits of n in reverse order. Your program should reject (politely) any input not in the appropriate
range.
For example if you enter the integer 123, the program should output the digits 321 one next to
the other.
Answer:
Problem:
Write a program that inputs a three digit integer n (no zero in the units position) and returns the
integer made up of the digits of n in reverse order. Your program should reject (politely) any
input not in the appropriate range.
For example if you enter the integer 123, the program should output the integer 321 (not just
Answer:
54
New Topic
Repetition and Loops
Additional Python constructs that allow us to effect the (1) order and (2) number of times that
program statements are executes.
These constructs are the
1. while loop and
2. for loop.
Recall:
1.
2.
3.
4.
Input
Output
Memory
Arithmetic – symbolic manipulation and evaluation
5. Control – we have already seen “straight line execution, and if statement.
We have seen a simple example of control. Python simply executes one statement after another
from the first statement of the program to the last i.e. straight line execution. In we have seen
how Python lets us execute statements conditionally. So if a Boolean condition is met, a given
block of statements is executed once, otherwise it is not.
But … what about the case that we want to execute the block multiple times, as long as the
Boolean condition is True? We can do this by using a
while loop.
Example:
Write a program that prints the numbers 1 – 10, one per line.
55
Solution: Use a while loop.
The syntax (form) of the while statement is:
while <Boolean expression> :
one or more statements (called a code block)
The semantics (meaning or interpretation) is:
Upon encountering the while statement:
1. Evaluate the Boolean expression
2. Repeat the associated block as long as the Boolean expression is True
3. Exit the while loop as soon as the Boolean expression evaluates to False.
Definition: This process of repeating one or more statements is called iteration.
Problem:
Write a program that asks the user for a positive integer n. It then prints the numbers 1 through n,
one per line.
Answer:
56
Problem:
Write a program that asks the user for a positive integer n. It then prints the numbers n down to
1, one per line.
Answer:
Problem:
Write a program that asks the user for a positive integer n (>= 2). It then prints the even numbers
in the range 1 to n, one per line.
Answer:
57
Problem:
Write a program that asks the user for a positive integer n. Print a triangle of “stars”( = “*”) like
in the example below.
Answer:
Problem:
Now do this one.
58
Problem:
Write a program that asks the user for a positive integer n. Calculate and print the sum of the
integers 1 through n.
Answer:
Problem:
Write a program that asks the user for a positive integer n. Calculate and print the product of the
integers 1 through n.
Answer:
Problem:
Write a program that asks the user for a positive integer n. Calculate and print the sum of the
odd integers in the range 1 through n.
Answer:
59
Problem:
Write a program to request and validate a password from your user. A valid password
will be any two digit integer, both digits of which are even.
Give the user three chances to enter a correct password.



At each incorrect attempt, print “Invalid password. Try again”
If the password entered is correct print “Correct! You may access the system.” Exit the
program.
If the password entered is incorrect print “Too many invalid attempts. Please try again
later.”
Answer:
60
Problem:
Write a program that asks the user for a positive integer n where the right-most digit is not a
zero. Print out the digits of n from right to left – one next to the other.
Answer:
Problem:
Write a program that asks the user for a positive integer n where the right-most digit is not a
zero. Construct and output the integer whose digits are the reverse of those in n.
For example, if n has the value 123, then you need to construct the integer 321. Note you are not
just printing the digits of n in reverse order; you are actually constructing the new integer.
Answer:
1. What is the algorithm (method)?
61
2. Write the code.
Problem:
Recall the definition of a prime number:
An integer greater than one is called a prime number if its only positive divisors (factors) are one
and itself.
Write a program that inputs a positive integer n and determines if n is prime or composite (i.e.
not a prime).
Answer:
62
We now look at the second loop structure in Python, the
for loop
Example:
Write a program that prints the numbers 0 – 10, one per line.
Answer:
This is the simplest usage of the for statement. It lets you iterate over a sequence of numbers. In
the example above, the sequence starts implicitly at 0 and goes up to, but not including 11.
The syntax (form) of this form of the for statement is:
for <some variable> in range(…) :
one or more statements (called a code block)
The semantics (meaning or interpretation) is:


The variable after the “for” takes on each value in the “range” successively.
That value may be used in the block that is the body of the for statement.
63
Question: What about the range function?
Here are some examples:
and
range(…) has the following syntax:
range([start value,] end value [,step])
and the following semantics:
1. if start value



> end value:
Generate a sequence of values starting with the start value
generate each subsequent value by adding “step” to the previous one
the last value in the sequence is the largest number less than end value.
Note: The default value of “step” is 1.
64
2. if start value



< end value:
Generate a sequence of values starting with the start value
generate each subsequent value by adding “step” to the previous one
the last value in the sequence is the smallest number greater than end value.
Note: In this case the value of “step” should be negative.
Example: The following code:
prints:
Use a for loop to solve the next set of problems.
Problem:
Write a program that asks the user for a positive integer n. It then prints the numbers 1 through n,
one per line.
Answer:
65
Problem:
Write a program that asks the user for a positive integer n. Calculate and print the sum of the
integers 1 through n.
Answer:
Problem:
Write a program that asks the user for a positive integer n. Calculate and print the product of the
integers 1 through n.
Answer:
Problem:
Write a program that asks the user for a positive integer n. Calculate and print the sum of the
odd integers in the range 1 through n.
Answer:
66
Problem:
Generate and print all numbers between 1 and 1000 such that the sum of the digits equals 20.
Answer:
Problem:
Generate and print all prime numbers between 1 and 100.
Answer:
67
Problem:
Write a program using for loops to print the following:
Answer:
68
Problem:
Write a program, using for loops, to generate the following output.
Answer:
69
How do we control statement execution inside a loop (either while or
for)? Two new ways.
Until now:
while loop:
We keep executing the body of the loop as long as the Boolean expression in the loop head is
true. We exit only when it becomes false.
for loop:
We keep executing the body of the loop as long as the sequence of values in the range() function
has not been exhausted. We exit only when there are no more values generated in conjunction
with the “argument list”.
However …. Python has two other statements that allow us to control what happens inside a
loop:
1. continue
2. break
1. continue: When Python encounters a continue statement inside a loop, the interpreter
proceeds directly to the top of the loop, skipping all the statements in the after the continue.
For example this code
produces this output:
Question: What would be printed if the if and continue are left out?
70
2. break: When Python encounters a break statement inside a loop, the interpreter causes the
loop to terminate and execution of the program continues with the first statement after the loop.
For example this code
For example this code
produces this output:
Question: explain this output in detail, including the blank line between the tuples printed.
71
Here is an attempt to re-write the “continue” example with the for loop except using a while
loop:
example
Question: What will be printed? Why?
If instead of a continue statement in the code above, we put a break, like this:
we get
Why?
72
New topic
Modules and Functions
We have already seen that Python provides built-in function that we can use:
These functions are available directly from the interactive shell. But …. say we want to get the
square root of a number. It would seem reasonable that Python would provide a function to do
that as well.
But when I try to use what I think should work, I get this:
But the following will work.
Why?
“math” is a module (= a file) containing a number of mathematical functions.
The “import” statement instructs Python to “load” the module and make these functions
available for use.
73
Which functions are available in the math module?
We do it with the “dir” command:
If we want to know what each one of these function does we use the “help” command:
And it goes on and on ..
You can also get help on a single function:
74
How do we use functions in a module?
There are three ways.
1. The way we just saw: This just makes the module available but we need to use the “dot”
syntax to actually access the function.
2. We can import a single function from a module. The function is then available to be used
“directly” like the len() function.
3. We can import all the functions from a module at one time. We can then use the function
name directly as in 2 above.
Question:
What are the advantages and disadvantages of each of the methods above?
Answer:
We can also do this:
75
We can create our own functions and modules!
But why would we want to? There are a number of reasons.
Answer:
How do we create functions? Easy. We use “
def:
IMPORTANT: Terminology: The x any above are called parameters, the 3 and 4 are called
arguments. The arguments can be constants as in the above example, or variables as in the
examples below.
76
Here is the syntax.
def function_name( parameter list): # the parameter list could be empty – but still need ().
code block
And the semantics:
1. A function needs to be defined, using the “def” construction above, before it is used.
Otherwise Python will issue an error like this:
2. The parameter list is a list of variables that will refer to local copies of the arguments “passed”
from the calling code. For example:
Notice1: The variables in the parameter list are local. This means that any changes that you
make to them in the function do not affect the values in the corresponding arguments in the main
program. What happens in Vegas ….
Notice2: The actual story is a bit more subtle than Notice1. We have passed in simple types.
Stay tuned for what happens later on.
77
Question: How does a function return a value back to the “caller”?
Answer: It uses the “return statement”. It has two forms:



return <some value>
return
or … the function just “falls off” the last statement and implicitly returns to the
caller.
The first form terminates the function and makes <value> available at the place from which the
function was called. Program execution resumes from that point as well.
The second form just terminates the function, and computation resumes from the point from
which the program was called.
The third “form” behaves just like the one above.
Terminology: When a function doesn’t return a value, but rather performs some function for us,
we will sometimes call it a procedure.
This tells us that the len() function returns an int.
But the print function returns “NoneType”, a catchall that says that the function returns nothing.
The print function is not computing a value for us, it’s basically “doing a job” for us, and then
returning to the caller. We will call this a procedure.
Problem:
Write a function is_even(x) which returns True if x is even and False otherwise.
Answer:
78
Problem:
Write a function is_leap(x) which returns True if x is a leap year and False otherwise.
Answer:
Problem:
Write a function is_prime(x) which returns True if x is a prime number and False otherwise.
Answer:
79
Problem:
Write a program to ask the user for two integers, first and last. Write a program to print out all
the primes between first and last (inclusive), five values per line.
Answer:
Problem:
Write a function sum_of_digits1(n) which returns the sum of the digits of n.
Answer:
80
Problem:
Write a function sum_of_digits2(n) which prints the sum of the digits of n.
Answer:
Just like there are conversions, int, float, str, there is a built in function called bin. The
documentation says:
bin(x)
Convert an integer number to a binary string.
For example:
Problem:
Write a function my_bin(n) which converts an integer number to a binary string representation of
n. But Leave out the leading ‘0b’ returned by the built in function bin.
Answer:
81
Global Variables
Question: How can we get functions to change the values in variables outside of themselves?
We have already seen that variables in a function are local, so changing them doesn’t affect (in
the instances we considered) the arguments passed over. But what about other variables, like in
the following example?
We get:
but if we add a global statement:
we get:
82
Lists Strings, Tuples and Other Sequences
The following 2 pages are for reference.
Sequences represent ordered sets of objects indexed by nonnegative integers and include
strings, (including Unicode strings) lists, and tuples. Strings are sequences of characters, and
lists and tuples are sequences of arbitrary Python objects. Strings and tuples are immutable; lists
allow insertion, deletion, and substitution of elements. All sequences support iteration.
Don’t worry! All the strange terms above will be explained below.
Operations and Methods Applicable to All Sequences
Item
Description
s[i]
s[i:j]
Returns element i of a sequence
Returns a slice
s[i:j:stride]
Returns an extended slice
len(s)
min(s)
max(s)
Number of elements in s
Minimum value in s
Maximum value in s
Operations Applicable to Mutable Sequences
Item
s[i] = v
s[i:j] = t
s[i:j:stride] = t
del s[i]
del s[i:j]
del s[i:j:stride]
Description
Item assignment
Slice assignment
Extended slice assignment
Item deletion
Slice deletion
Extended slice deletion
Lists are sequences of arbitrary objects.
You create a list as follows:
names = [ “Dave”, “Mark”, “Ann”, “Phil” ]
Lists are indexed by integers, starting with zero. Use the indexing operator to access and modify
individual items of the list:
a = names[2] # Returns the third item of the list, “Ann”
names[0] = “Jeff” # Changes the first item to “Jeff”
To append new items to the end of a list, use the append() method:
names.append(“Kate”)
83
To insert an item in the list, use the insert() method:
names.insert(2, “Sydney”)
You can extract or reassign a portion of a list by using the slicing operator:
b = names[0:2] # Returns [ “Jeff”, “Mark” ]
c = names[2:] # Returns [ “Sydney”, “Ann”, “Phil”, “Kate” ]
names[1] = ‘Jeff’ # Replace the 2nd item in names with ‘Jeff’
names[0:2] = [‘Dave’,’Mark’,’Jeff’] # Replace the first two items of
# the list with the list on the right.
Use the plus (+) operator to concatenate lists:
a = [1,2,3] + [4,5] # Result is [1,2,3,4,5]
Lists can contain any kind of Python object, including other lists, as in the following example:
a = [1,”Dave”,3.14, [“Mark”, 7, 9, [100,101]], 10]
Nested lists are accessed as follows:
a[1] # Returns “Dave”
a[3][2] # Returns 9
a[3][3][1] # Returns 101
List Methods
Method
Description
list(s)
s.append(x)
Converts s to a list.
Appends a new element, x, to the end of s.
s.extend(t)
Appends a new list, t, to the end of s.
s.count(x)
s.index(x [,start [,stop]])
Counts occurrences of x in s.
Returns the smallest i where s[i] ==x.
start and stop optionally specify the start- ing and ending index for
the search.
Inserts x at index i.
s.insert(i,x)
s.pop([i])
s.remove(x)
Returns the element i and removes it from the list. If i is omitted,
the last element is returned.
Searches for x and removes it from s.
s.reverse()
Reverses items of s in place.
s.sort([cmpfunc [, keyf [, reverse]]])
Sorts items of s in place. cmpfunc is a
comparison function. keyf is a key function. reverse is a flag that
sorts the list in reverse order.
84
We will start with
Lists
A list in Python is a mutable sequence of any time of Python object.
What does this mean??
Example:
x=[1,23,”hello” , [3.4]]
x is the name of the list. It has 4 elements:




the integer 1
the integer 23
the string “hello”
the list [2,3]
It looks something like this in memory.
85
We create a new empty list in one of two ways:
 x=[]
 x=list()
or, as above, we can create a list with elements just by listing the elements in the square brackets
“[“ , “]”.
Question:
How do we access individual elements of a list?
Answer:
We use square brackets with an integer to “index” into the list. For example:
Notice:
1. The positions in the list are numbered from 0 (not 1). In the above example, this means that
the last element in the lost is accessed as x[3].
2. Since x[3] in our example is the list [3,4] we can access its elements by using a second index.
That is why x[3][0] is the “zeroth” (i.e. first) element of [3,4], which is 3.
3. Since there is no element in the list x[4] (they are x[0], x[1], x[2], x[3]) we are trying to access
a nonexistent element and Python prints an error message.
Question:
Can we change (i.e. replace) elements of a list?
Answer:
Yes. Here is an example where we modify the list x above.
86
We can find out the size (=length) of a loop by using the len() function:
We say that a list is mutable. This means that is can be modified (i.e. “mutated).
Question:
How can we add elements to an existing list?
Answer:
There are a number of different ways. We start with two functions:


append – add “something” to the end of a list
extend – add all the elements of some sequence at the end of a list
87
Make sure the example above is absolutely clear!
Lists and loops
List and loops are made for each other!
Problem:
Write a program that creates a list with the integers 1 – 10. Using a for loop add up all the
elements of the list and print the sum.
88
Problem:
Write a program that creates a list with the integers 1 – 10. Using a for loop, add up all the
elements of the list that are even and print the sum.
Problem:
Write a program that creates a list with the integers 1 – 10. Using a for loop add up all the
elements of the list that are odd and print the sum.
Problem:
Write a program that creates a list with the integers 1 – 10. Using a for loop add up all the
elements of the list that are in even positions ( 0 is even) and print the sum.
89
When using lists it is often convenient to have Python generate some random values for us.
Python provides a module called random that has some useful functions for this purpose. The
two that we will use most are:


random and
randint
So ..
Function “random()” generates a random floating point number from zero up to but not
including one.
Function randint(a,b) generates a random integer in the range a to b inclusive. Note that a and b
here are integers.
Problem:
Write a program to fill a list of size 10 with random integers in the range 1 – 10 and print it out.
90
Problem:
Modify the program above so that we print the list as well as the maximum integer in the list. Do
this two ways.
Problem:
Modify the program above so that it also prints the position in the list where the maximum
element was found.
91
Problem:
Using the code from the program above write a function
getmax(x,i) #x is a list and i is an integer
which will find and return the maximum element among the first i elements of list x.
getmax will return two values:


the maximum element found, and
the position in list x where that element was found.
For example, say a=[4,2,7,1,45,23], then getmax(a,4) will search for the maximum element in
the first 4 element of list a.
So, in this case it will look at the following numbers: 2,4,7,1, and getmax(a,4) will return 7,2.
This because in the first 4 elements, the largest is 7 and it is in position 2.
If we ran getmax(a,6) the function will return 45,4.
92
Problem:
Generate all the primes between 2 and 100.
Solution:
The Sieve of Eratosthenes provides an efficient solution. This algorithm is over 2200 years old!
Here is the Wikipedia description: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
See there for an animation of the algorithm.
To find all the prime numbers less than or equal to a given integer n by Eratosthenes'
method:
1. Create a list of consecutive integers from 2 through n: (2, 3, 4, ..., n).
2. Initially, let p equal 2, the first prime number.
3. Starting from p, enumerate its multiples by counting to n in increments of p, and mark
them in the list (these will be 2p, 3p, 4p, etc.; the p itself should not be marked).
4. Find the first number greater than p in the list that is not marked. If there was no such
number, stop. Otherwise, let p now equal this new number (which is the next prime), and
repeat from step 3.
When the algorithm terminates, all the numbers in the list that are not marked are prime.
Why does it work?
The main idea here is that as we go through the algorithm, every value for p is prime, because we
will have already marked all the multiples of the numbers less than p. Note that some of the
numbers being marked may have already been marked earlier (e.g. 15 will be marked both for 3
and 5).
The program below is a slight modification of the above algorithm.
This program will generate all primes in the range 2-100 using the sieve method.
We use two lists: x and primes.
list x will initially have the values 0-100 so that x[i]=i
list primes, initially empty, will grow as each new prime is found and appended onto it.
Each time a new prime p in x is located:



p will be appended to list primes
its place in list x will be set to zero,
set all of its multiples in list x will be to zero.
When all elements in x are zero (we check this with the sum function), the main while loop
terminates and the program prints list primes.
93
x=[]
for i in range(101):
x.append(i)
primes=[2]
x[0]=x[1]=x[2]=0
p=2 # the first prime
while sum(x) != 0: # as long as sum(x)!=0, there are still non-zero entries in x.
# Zero out all multiples of p
i=1
while i*p<=100:
x[p*i]=0
i=i+1
# Now, look for the next prime
p=p+1
while x[p]==0: # it’s at the next non-zero position of x
p=p+1
# We found it. Add it to the list of primes, and zero out its position in x
primes.append(p)
x[p]=0
# Done! Now print the list of primes.
print(primes)
94
Let’s take a break!
Here is a really interesting
Microsoft/Google/Wall Street Interview Question!
1. Run the following program:
from math import sqrt
from random import random
count=0
for i in range(1000000):
x=random()
y=random()
if sqrt(x*x+y*y)<1:
count+=1
print(4*(count/1000000))
2. What is it calculating?
3. How/why does it work? What is the theory behind this?
95
Sorting
Sorting is an operation on a list that orders the list elements in a specific order.
For example:
1. A list of names may be sorted in “lexical” =dictionary=alphabetical order.
Here is a formal definition of lexical order from Wikipedia:
The name of the lexicographic order comes from its generalizing the order given to words in
a dictionary: a sequence of letters (that is, a word)
a1a2 ... ak
appears in a dictionary before a sequence
b1b2 ... bk
if and only if at the first i where ai and bi differ, ai comes before bi in the alphabet.
That comparison assumes both sequences are the same length. To ensure they are the same
length, the shorter sequence is usually padded at the end with enough "blanks" (a special symbol
that is treated as coming before any other symbol).
Note that we can order the names in reverse order, from latest to earliest. In this case the words
still are in lexicographic order, but from the last element to the first.
2. A list of integers may be listed in either from smallest to largest or vice versa.
Why sort?
It turns out that sorting is one of the most important operations that programs perform. Two
examples.
1. Searching a list. In order to find a specific element I a list we often sort it first. A sorted list
can be searched much more quickly than one that is unsorted. Imagine looking up a phone
number in a phone book (list) with a million entries. If the list is unsorted, we might need to look
at 1,000,000 entries. If it is sorted, we don’t need more than 20.
2. A Scrabble dictionary. We might want to bring all the words with the same letters next to
each other in the list. So if we got the letters ‘opts’ we would like to have stop, pots, and tops all
next to one another. Imagine that we had a function called “signature()” that transforms each of
stop, tops and post  opts. Then if D is the list of dictionary words then
D.sort(key=signature)
would do this for us. We will actually do this later on.
96
Problem:
Given a list of integers, sort it so that its elements will be in ascending order.
Selection Sort
Here is the beginning of the Wikipedia entry. http://en.wikipedia.org/wiki/Selection_sort
The algorithm divides the input list into two parts: the sublist of items already sorted, which is
built up from left to right at the front (left) of the list, and the sublist of items remaining to be
sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist
is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on
sorting order) element in the unsorted sublist, exchanging it with the leftmost unsorted element
(putting it in sorted order), and moving the sublist boundaries one element to the right.
Here is an example of this sort algorithm sorting five elements:
64 25 12 22 11
11 25 12 22 64
11 12 25 22 64
11 12 22 25 64
11 12 22 25 64
Problem:
Using the getmax function above, write function
select_sort(x) # x is a list of integers
which performs select_sort on list x.
Solution:
def select_sort(x):
for i in range(len(x)):
m,pos=getmax(x,len(x)-i)
x[len(x)-i-1],x[pos]=x[pos],x[len(x)-i-1]
Notice that for the purpose of function select_sort() we don’t need the value of m that is
returned. However, we still need to “catch” it with two variables (in this case m and pos) , since
the function returns happens to return two values. In a different context we might actually use
both of the values that are returned.
97
Here is another elementary sort called
Bubble Sort
Here is the beginning of its Wikipedia entry.
Bubble sort, sometimes incorrectly referred to as sinking sort, is a simple sorting algorithm that
works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items
and swapping them if they are in the wrong order. The pass through the list is repeated until no
swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the
way smaller elements "bubble" to the top of the list.
The full article and an animation is here: http://en.wikipedia.org/wiki/Bubble_sort
Here is the code.
# Bubble Sort
def bubble_sort(a):
for i in range(len(a)):
sorted=True
for j in range(len(a)-i-1):
if a[j]>a[j+1]:
a[j],a[j+1]=a[j+1],a[j]
sorted=False
if sorted==True:
return
# Lets test it.
a=[33,6,3,21,88,30]
print(a)
bubble_sort(a)
print(a)
.
98
Sorting … a third way, using Python’s built-in sort function.
L is a list.
Notice: function sort() takes 2 optional key word arguments:


key
reverse
key specifies a function of one argument that is applied to the list elements before the
comparison is made.
reverse specifies that the list should be in reverse order. That means that “>” is used for
comparison rather than “<”.
Why is it called a “key word argument”?
Because if you want to use it, you need to use the “keyword=value” syntax. We will see this
below.
Say, for example, we want to sort a list of strings. String comparison depends on
capitalization as in the following example. If we wanted to discount the capitalization in the
comparison we could use the lower() function.
The default value for key is None.
99
Now, let’s sort a list of strings.
What about the keyword argument “reverse”?
Here is an example.
100
Problem:
Given a list, print the elements of that list in reverse order. Do this in two ways.
Problem:
Given a list reverse the elements of the list. For example if
x=[1,2,3], then after it is reversed x would be [3,2,1].
Do this in two ways.
101
Slicing lists
What is a slice of a list?
If x is a list then the slice x[a:b]is the “sub-list” of the elements of the elements of a from
index position a up to but not including index position b.
If we want to indicate that the slice starts at the beginning of the list, we can leave out the start
value:
If we want to indicate that the slice goes all the way to the end of the list, we can leave out the
end value:
Leaving out both the start and end indexes is the same as saying the whole list. So:
102
What can we do with a slice of a list?
1. As we saw above, we can create a new list form a slice.
2. We can assign to a slice and thereby replace one sub-list by another.
Notice that this is a generalization of accessing and replacing one list element as in a[1]=12
which just replaced a single list element.
When we use a slice we can indicate a stride.
Huh?
The stride is the length of the “step” that you take going from one element to the next when
creating the slice.
In the following example 2 is the stride.
We can assign to a slice with a stride, but the list on the right hand side of the assignment must
be the same size as the list produced by the slice. In the following example, both are of size 4.
103
Two dimensional lists
Many important applications use data that is represented in a 2-dimensional table.
How do we represent this in Python?
We simply use a list of lists.
a=[ [10,20,30],[40,50,60],[70,80,90] ]
Notice that the length of list a is 3 (len(a)==3), but it’s made up of three lists, each one of length
3.
Problem:
Change element with a 50 to 500.
Solution:
The 50 is the second element of the second list. Recalling that lists are indexed starting with 0,
we write:
104
Nested loops and two dimensional lists
Even though a list is “really” is a list of lists, when we program its useful to think of it as a two
dimensional table.
So, for the list a above, we can consider it a table with three rows and three columns. The
rows and columns are each indexed starting at 0. We will say that he position with entry 500 is
at row 1 and column 1.
We saw how lists and loops are “made for each other.” The same is true with two dimensional
lists (we will sometimes refer to the as two dimensional “arrays”. This is what they are called in
many other programming languages (though they are implemented differently).
Problem:
Print list a above so that each “row” of it prints a separate row.
And formatted …
105
Problem:
Create a 4X4 array and initialize each of the elements to 0.
Solution:
a=[]
for i in range(4):
a.append(4*[0])
What does 4*[8] mean?
Python lets us use + and * with lists.
So from here you see + is concatenate i.e. it acts like the list function extend. But you
can only + a list to a list, not a string to a list like you can with extend.
What about “*” ?
106