Lecture 6
Lecture 6
• Python will evaluate each condition in turn looking for the first one that is
true. If a true condition is found, the statements indented under that
condition are executed, and control passes to the next statement after the
entire if-elif-else.
• If none of the conditions are true, the statements under the else are
performed.
• The body of the loop executes repeatedly as long as the condition remains
true. When the condition is false, the loop terminates
Nested Loops
Again in the number averaging example, suppose instead of one-per-line we
allow any number of values on a line, separated by comma.
Post-Test Loop
Suppose you are writing an input algorithm that is supposed to get a
nonnegative number from the user. If the user types an incorrect input, the
program asks for another value. It continues to reprompt until the user enters
a valid value. This process is called input validation.
•Words in a document.
•Students in a course.
•Data from an experiment.
•Customers of a business.
•Graphics objects drawn on the screen.
•Cards in a deck.
Example problem: simple statistics
Extend this program so that it computes not only the mean, but also the
median and standard deviation of the data
Basic summary statistics
Lists
• Lists are ordered sequences of items, a collection of values denoted by the enclosing square brackets
• Second, lists are mutable. That means that the contents of a list can be modified. Strings cannot be changed “in place.”
Tuples
• A tuple is a sequence of immutable Python objects.
Just like lists. The only difference is that types
cannot be changed.
• Tuples are defined using parentheses while lists
use square brackets.
• Examples:
Tup1 = (1,2,3,4)
Tup2 = (‘UCI’, ‘UCLA,’UCSD’)
List operations
• Python lists are dynamic. They can grow and shrink on demand. They are also
heterogeneous. You can mix arbitrary data types in a single list. In a nutshell,
Python lists are mutable sequences of arbitrary objects. This is very different
from arrays in other programming languages.
• A list of identical items can be created using the repetition operator.
• Typically, lists are built up one piece at a time using the append method.
List operations: remove elements
List operations
Using lists is easy if you keep these basic
principles in mind
• A list is a sequence of items stored as a single object.
• Lists are mutable; individual items or entire slices can be replaced through
assignment statements.
x = [1,2,3,4]
y = x
y[1] = ‘hello’
>>> y
[1,’hello’,3,4]
>>> x
[1,’hello’,3,4]
>>> x = [1,2,3,4]
>>> my_func(x)
>>> x
[1,2,3,4,’hello’]