Introduction to Programming

A Program...

To make a program do something, you have to put it in a way where the computer knows what to do with it.
It has to be given instructions in a specific sequence in order for the computer to know what it needs to do.

Python is an interpreter, you write your program in python, and python interprets it and feeds it to the computer. (An interpreter follows the instructions in your code and it does that by following the instruction in its code.)

Your First Program

And now to write your very first program using Print. Print is a Python command that displays something onscreen.

print 3

Believe it or not, that - is a program. When run in the Python Interpreter, it will display a result, in this case the number 3.

Okay, that wasn't impressive. (Or maybe you have low expectations and it was?) So here are a few more things to try:

  • print 7 * 3 * 4 + 17 (Python can do arithmetic, in this case, multiplying 7 times 3, then that result times 4, then that result plus 17.)
  • print (52 * 3) + (12 * 9) will allow you to control the math via the usual BEDMAS rules.

Quiz - Operating and Expressing

Get Python to Calculate and Display the number of minutes in 7 weeks.

print 60 * 24 * 7 * 7

What this did was multiply 60 (Number of minutes in an hour) by 24 (Number of hours in a day) by 7 (Number of days in a week) by 7 aagain (Number of weeks we want to calculate)

Express Youreself

An Expression is something that has a value. An expression can be a number, for example.

An Operator is an action that you can apply against/to an Expression. An example of an operator is + or * (add or multiply)

Quiz - Speed of Light

Speed of Light = 299,792,458 meters/second
Meter = 100 centimeters
Nanosecond = 1/1,000,000,000

print 299792458 * 100 * 1.0/1000000000

A more detailed explanation of the Python code here: 299792458 * 100 * 1.0/1000000000 * 1/2.7

The first term is the speed of light in meters per second (this is actually exact - a meter is defined as "the length of the path travelled by light in vacuum during a time interval of 1/299 792 458 of a second.".
The second term, 100 is the number of centimeters in a meter.
The third term, 1.0/1000000000 is one billionth. (Note that we need the .0 here (or at least 1.) to make Python do floating point division. Otherwise, 1/1000000000 would evaluate to 0.)

So, the first three terms in the product compute the distance in centimeters that light travels in one billionth of a second (or one nanosecond). To compute the number of nanoseconds per cycle for my 2.7 GHz processor, the fourth term is 1 / 2.7. Since there are 2.7 Billion cycles per second, there are 2.7 cycles per nanosecond, and each cycle takes 1 / 2.7 nanoseconds.


Python requires code be written with a very specific syntax. This means that small typos can lead to big problems!

The trick to dealing with programming mistakes (called "bugs") is not to avoid making them entirely. That's impossible. The trick is to develop a system for finding and fixing them.

For more details about debugging, there's a great article on Stack Overflow that goes into better detail.


Variables and Strings


Instead of just hard coding in a value or an Expression, you can use Variables, which act kind of like a placeholder for the value that you want to put there, but might not be the same value every time.

To specify a variable, you need to have an assignment statement: assigned_name = variable_value

Assigned_name is what you use to call the variable. Variable_value is the value that the variable contains. Can be a number, a string, etc.

Quick note: In programming context, "=" does not mean 'equals' ... it means 'assignment' ... so think of it more like an arrow, not as an equals sign. Another way to think of '=' can be 'is'...

An example of setting the value of a variable is: speed_of_light = 299792458

Quiz - Vary Able

speed_of_light = 299792458 #meters per second
cycles_per_second = 2700000000. #2.7ghz speed (the . at the end makes it an integer)

speed_of_light = 299792458.0
cycles_per_second = 2700000000.0
#The solution is to divide SOL by CPS
print speed_of_light/cycles_per_second

Quiz - Time After Time

hours = 9
hours = hours + 1
hours = hours * 2

After running the code: hours = 20

Quiz - On Second Thought

minutes = minutes + 1
seconds = minutes * 60

After running this code, the value of seconds is = an error (because minutes is not defined)

Quiz - Age is a Number

# Write python code that defines the variable
# age to be your age in years, and then prints
# out the number of days you have been alive.

days = 365
age = 36
alive = days * age
print alive

Instructor Answer:
age = 40
days_in_year = 365.25
print age * days_in_year + 268

(Why the 268? That's the calendar day for the exact date of the year it is for the time the answer is written)

Silly String

A string is a sequence of characters, surrounded by quotes.

'I am a string!'
"I am a string!"

You can use single or double, just as long as you close them with the same quote.
It's useful because: "I'm happy" works as a string, whereas 'I'm happy' would throw an error.

Some more examples:

print 'hello'
print "hello"
print hello

The First 2 hellos will print, the third will throw an error, since it is thinking its a variable, and well, we didnt define the variable.

Quiz - Stringy Business

Define a variable - name, and assign it to a string that is your name.

name = "Nelson"
print name

Come more examples and things to consider:

print 'Hello' + name

The "+" basically concatenates the values together. Problem is, when you run it, it will spit out HelloBob. To fix it...

name = "Bob"
print 'Hello ' + name #notice the added space next to hello, in the quotes

Something else to try:

name = "nelson"
print 'Hello ' + 9

Running that will error out. Why? Because 9 is treated as a number in this case, not as a string. To fix it:

print 'Hello ' + '9'


More about strings, is you can index a string. What that is, is you can call specific parts of a string value, to use in other ways. The syntax is something like this:

'string' [expression]

'udacity' [0] -> 'u'
'udacity' [1+1] -> 'a'

To see this in practice:

name = 'Nelson' print name[0]

Running that would result with: N
N is the value of the string at position 0. e is position 1, l is position 2, s is position 3, and so on.
Some more insight into this...

name = 'Nelson'
print name[-2]

Running this results in o... when you use -2 as an example, it starts at the end of the string and works backward.

The Sub-Sequence

A sub-sequence looks something like this: <string>[<expression>:<espression>] but here's some examples in use:

word = 'assume'
print word[3]

Running that would result in 'u'.

word = 'assume'
print word[3:3]

Results in nothing, since there is no character between position 3 and 3

word = 'assume'
print word[4:6]

Results in 'me' since it falls between there. (It gives you values for position 4 and position 5)

word = 'assume'
print word[4:]

Results in 'me', it selects position 4 to the end.

word = 'assume'
print word[:2]

Results in 'as', it selects position 0 and 1, but not position 2.... confused yet?

Sub-Sequence Examples

Here are just a few more examples of string sequencing just to hammer home the concept.

# Imagine you wanted to write code that extracted the
# text from an HTML div...

html_div = "<div>This is some text</div>"
div_text = html_div[5:-6]

print div_text

# Can you modify the code below to print out the text
# inside of an HTML <b> element?

html_b = "<b>And this is even more text</b>"
b_text = html_b[:] #this is the line you should modify
print b_text

(Answer to that last bit:)
html_b = "<b>And this is even more text</b>"
b_text = html_b[3:-4] #this is the line you should modify
print b_text

Quiz - Make it so, Cap

# Write Python code that prints out Udacity (with a capital U),
# given the definition of s below.

s = 'audacity'
cap_u = 'U'
print cap_u + s[2:8]

Instructors Answer:
print 'U' + s[2:]

(2: lets you just use from position 2 to the end of the string)

The Find Method

The .find method allows you to find a sub-string within a string.

The syntax for using .find looks something like this: target_string.find('value you want to find in the target string')

**Note: Using this will search the target string going from left to right (starting at position 0). If there are multiple matches to your 'find', it will only return the first match position. If it does not find a match, it will return a "-1".

Examples of FIND

Here is an example of how .find works...

pythagoras = 'There is geometry in the humming of the strings, there is music in the spacing of the spheres.'
print pythagoras.find('string')

The result after running this will be 40. This means that it found a match for the value string, and that match was first found at position 40.

Quiz - Find it Yourself

Which of the following evaluate to -1?

  • 'test'.find('t')
  • "test".find('st')
  • "Test".find('te')
  • 'west'.find('test')

And now for the answers, and why:

  • 'test'.find('t') -- Evaluates to 0 (It found a match for 't' at position 0)
  • "test".find('st') -- Evaluates to 2 (It found a match for 'st' at position 2)
  • "Test".find('te') -- Evaluates to -1. The .find is case-sensitive, and therefore won't match
  • 'west'.find('test') -- Evaluates to -1. The value of 'test' cannot be found in the string of 'west'.

Quiz - How Find is Defined

For any string, which will always have a value of 0? s="any string"

  • s.find(s)
  • s.find('s')
  • 's'.find('s')
  • s.find('')
  • s.find(s+'!!!')+1

Confused? Yeah, same. Here's an explanation of the answers:

  • s.find(s) -- The value of the find is equal to the string itself, so the first value will always be the same, even if no values are in the string.
  • s.find('s') -- if the string was hello, this wants to find 's' (because of the quotes) in hello, which it doesnt find.
  • 's'.find('s') -- the first 's' is a string with a value of s... so the find of 's', is true, and is at position 0 always.
  • s.find('') -- we're looking for an empty string here ''... so this will always be zero.
  • s.find(s+'!!!')+1 -- Tricky. The (s+'111') will never be found (because of the +'111')... so it results in -1... but because we also add 1 after, its value is going to be 0. Crazy eh?

The Find Playground

You can play with some more examples using Udacity's wonderful Python Interpreter.

# This segment is just a chance for you to play around with
# finding strings within strings. Read through the code and
# press Test Run to see what it does. Is there anything
# interesting or unexpected?

print "Example 1: Finding substrings in a string"
print "test".find("te")
print "test".find("st")
print "test"[2:]

print "Example 2: Finding substrings in a string which is stored as a variable"
my_string = "test"
print my_string.find("te")
print my_string.find("st")
print my_string[2:]

print "Example 3: Printing out everything after a certain substring"
my_string = "My favorite color: blue"
color_start_location = my_string.find("color:")
favorite_color = my_string[color_start_location:]
print favorite_color # oops, this line prints out 'color: ' as well...
print favorite_color[7:] # this fixes it!

print "Example 4: Other interesting things about string.find()..."
print "text".find("text") # prints 0
print "text".find("Text") # prints -1
print "text".find("") # prints 0
print "text".find(" ") # prints -1

Multiple Parameters

What's a parameter? In this code: "text".find("t") the "te" is a parameter. An example of multiple parameters can be something like:

"text".find("t", 1)

There are two parameters, "t" and 1. But what do they mean? Well the first parameter we already know. It's searching for a substring value of 't' within a target string. But the 1? That tells the find to start at position 1 and thereafter.

Here are some more samples of multiple parameters and how they work. Just plug them into the Python Interpreter and see what they do.

print "Example 1: using find to print the second occurrence of a sub-string"
print "test".find("t")
print "test".find("t", 1)

print "Example 2: using a variable to store first location"
first_location = "test".find("t") # here we store the first location of "t"
print "test".find("t", first_location+1) # then we use that location to find the second occurrence.

print "Example 3: using find to get rid of exclamation marks!!"
example = "Wow! Python is great! Don't you think?"
first = example.find('!')
second = example.find('!', first + 1)
new_string = example[:first] + example[first+1:second] + example[second+1:]
print new_string # oops, I should probably replace the !s periods
new_string = example[:first] +'.'+ example[first+1:second] +'.'+ example[second+1:]
print new_string

Last-Minute Definitions

Method: A method (or message) in object-oriented programming (OOP) is a procedure associated with an object class. An object is made up of behavior and data. Data is represented as properties of the object and behavior as methods.

Procedure: A procedure is a section of a program that performs a specific task. Also, an ordered set of tasks for performing some action.

What is the difference between a 'function' and a 'procedure'?

A function returns a value and a procedure just executes commands.
The name function comes from math. It is used to calculate a value based on input.

A procedure is a set of command which can be executed in order.
In most programming languages, even functions can have a set of commands. Hence the difference is only in the returning a value part.


Input • Function • Output

Functionlly Functional

What exactly is a function?

A function takes an input , does something with the input, and then gives back a result (output).

As an example, you could create a function that takes some input values, and combines them together in a specific order, and outputs them in that order for you to use elsewhere. (Like in a webpage)

Inputs + Outputs

Functions rely on inputs to provide the user with an output.

An input, essentially is a value. It's "something" - it could be a string, a number/interger, could be text, could be an output from another funtion, a variable, and so on. It is something that your function needs so it can perform its processing, and produce an output.

Make or Use

What is the difference between making and using a function?

Functions are made by starting a line of code with the keyword def and then giving a function name followed by the function parameters in parentheses. These parameters will eventually be replaced by actual values when the function is used (called).

Here's an example of this:
In the "body" of the function, we write the code that specifies what to do with the input parameters. For example the following code could be the definition of a function called square:

def square(x):
answer = x * x
return answer

To use this function, we would write the name of the function, followed by the values we want to pass, in parenthesis.

print square(4)

So, print is there to display the result onscreen. "Square" is the name of the function. (4) is the input value that we want the "Square" function to use. What will happen is print will make the function square run. Square will take the value of 4, and pass it into (x). answer is the value of x * x. The x * x will multiply the value of x by itself, in this case 4. Return causes the function to produce an output of the value of the multiplication. Because we used print, it will display the returned value onscreen. In this case, it will display a result of 16.

Avoiding Repetition

How do functions help programmers avoid repetition?

You often would use a function to do the same thing over and over, without having to rewrite code. A function in a programming language is a program fragment that 'knows' how to perform a defined task. For example a function may be written that finds the average of three supplied numbers. Once written, this function may be used many times without having to rewrite it.

No Returns, Please

What happens if a function doesn't have a return statement?

When a function has a return statement, it basically causes the function to terminate (or end) there, by telling it to produce an output.

If you do not use a return statement however, Python does not know that function should produce an output, or what it should be outputting. As an example:

def add_two(x):
answer = x + 2

new_number = add_two(7)
print new_number

Result: --> None

And now here is the same function, but this time we add a return statement... see how it reacts differently as a result:

def add_two(x):
answer = x + 2
return answer

new_number = add_two(7)
print new_number

Result: --> 9

Quiz - It Does SUMthing?

What does the sum procedure do here?

def sum(a,b):
a = a + b

  • A) Nothing
  • B) Takes two numbers as its inputs and outputs their sum.
  • C) Takes two strings as its inputs, and outputs the concatenation of the two strings.
  • D) Takes two numbers as its inputs, and changes the value of the first input to be the sum of the two numbers.

Answer: A

The procedure sum() doesn't return the changed value of a. (Sum doesn't return values, it just adds things together.)

Quiz - Does it Do SUMthing Now?

Now what does the sum procedure do here?

def sum(a,b):
a = a + b return a

  • A) Nothing (We know now that it won't do 'nothing')
  • B) Takes two numbers as its inputs and outputs their sum.
  • C) Takes two strings as its inputs, and outputs the concatenation of the two strings.
  • D) Takes two numbers as its inputs, and changes the value of the first input to be the sum of the two numbers.

Answer: B, C

But why? Because you could pass variables/strings as more than just numbers, if you passed a string (non numbers) it would concatenate the two strings and output the concatenation string.

Here is some additional insight from Instructor Dave:

The reason the fourth choice is incorrect is because the sum procedure does not actually change the values of the inputs. In fact, it is impossible to write a procedure that changes the value of an integer or string input, since these types are immutable. That means that once we create an object of an integer or string type, there is nothing that can be done to change the value of that object. For example,

x = 17
z = 'hello'
any_mysterious_procedure(x, z)

After this code, we know the value of x is still 17 and the value is z is still 'hello' even though we know nothing about what the any_mysterious_procedure does.


Decisions and Repetiton: 'If' and 'While'

What IF...

In programming, you need tools to help your program make decisions. In this case, we will learn about IF. When you use an IF statement, it allows you to control which code gets executed when.

With IF statements, you have if, then the <expression>, and lastly the <code block>. For an if statement to execute the code block, the if statement must be True. In the event that the if statement is not true (False) -- the code block for that if statement will NOT be executed.

Here's an example to help visualize that...

def absolute(x):
if x < 0:
x = -x
return x

Okay, so what does that do?

Let's make x a value of -9. If -9 is LESS THAN than zero (which would be a negative number if this were true), then execute the code block.

The code block takes the negative value, applies a negative to it, cancelling it out, causing it to become positive, and then returns the positive value.

Now, if the value was 15... IF (15) is less than zero (it is not) -- the code block doesn't do anything to the number, as the code block won't be executed, it will just return the number (15).

Code Example

# Read through the following code examples and try to predict what
# they will do. Press Test Run to see how close your prediction was.

# This is an example of a "While Loop". What do you think
# this code will display when you press Test Run?

counter = 0
while counter < 10:
print counter
counter = counter + 1

# This is a function that uses 'if' and 'else' to modify the
# behavior of the function based on what the input is.

def pluralize(word):
last_letter = word[-1]
if last_letter == 'y': # note the double equals sign ==
new_word = word[:-1] + 'ies'
new_word = word + 's'
return new_word
print pluralize('daisy')
print pluralize('rock')

Equality Comparisons

Generally, when we are comparing values, we want them to be the same type. For example, we will usually compare integers with other integers, strings with strings, etc. We can, however, compare two values of different types:

a = 1
b = 'hello'

print a > b

>>> False

print b > a

>>> True

Seems weird that this works, right? Also, why does Python decide that a string 'hello' is "greater than" 1? This was actually a mistake in Python 2, which has been fixed in Python 3. These comparisons will return consistent, but irrelevant results.

Python includes a lot of functionality to make comparisons. <em>Comparison Operators</em> such as <b>></b> (greater than), <b><</b> (less than), <b>==</b> (is equal to), <b>!=</b> (not equal) and so on.

If you were to use a comparator against 2 number values, such as <number> <operator> <number> ... the result would not be a number. Since you are not performing arithmetic in this operation, but instead a comparison. Now, the resulting value would be a BOOLEAN. Meaning True or False.

Here's an example:

print 9 == 8

The result is False. 9 is obviously not equal to 8.

True OR False?

Using the OR operand - <expression> or <expression>

If the first expression evaluates to True, the value is true, and the second expression is not evaluated. For example:

print True or What_Is_This

The True is true, and it doesn't look at What_Is_This... now, if True was in lowercase, it would be false (for reasons)... so the OR would kick in and look at What_Is_This ... and error out.

While Loops, While Loops, While Loo...

WHILE loops to make code that performs the same task many times. As long as the code block meets True as a condition, the code runs until the True condition is broken.

The syntax for a while loop is as follows:

while <testExpression>:

In other words, when while is being executed, it checks if the test expression is true, if yes, then it executes the code block, once it does that, it goes back to check if the test expression is true, and if so, runs the code block again, and continues this until the test expression is no longer true.

As an example to this...

i = 0
while i < 10:
print i
i = i + 1

Looking at this example, you set the variable of i to 0. Now, while will run as long as the value of i is less than 10. When true, it will print the value to the terminal, but then -- it adds 1 to the value of i. It will continue to add +1 to the value of i while the value of i is less than 10.


No rest for the wicked. Now we will learn about 'break' statements. Break allows you to stop the loop, even while/though the while condition is still true.

Here's an example of the syntax for a break statement in a while loop:

while <test expression>:
<code block>
if <breakTest>:
<more code in the while loop code block>
<code to execute after 'while' is no longer true, or if the breakTest is true>

And here's a working example:

Original code:

def print_numbers(n):
i = 1
while i < n:
print i
i = i + 1

You can break it to stop printing after the break check result is true:

def print_numbers(n):
i = 1
while True:
if i > n:
print i
i = i + 1

So what that does... it checks if i is less than n... if it is, carry on with the rest of the while code. However, if i is not less than n -- stop executing the while code (which in this case will stop the whole function after the break)


Structured Data: 'Lists' and 'For' Loops

Hello Lists

String - A sequence of characters (which you can run operators against)
List - A sequence of anything, characters, strings, numbers, other lists...

An example of a string: 'yabba!'
And a string as a variable: s = 'yabba!'

An example of a list: ['y','a','b','b','a','!']
And an example of a list as a variable: p = ['y','a','b','b','a','!']

To select elements in a String: s[0]
For example, s[0] selects the first value in the string.

To select elements in a List: p[0]
That selects the first element of the list P which is Y

To select a subsequence of more than one character in a string: s[2:4]
That will return the values of position 3 and 4, which is BB

To select a subsequence of more than one character in a list: p[2:4]
But instead of getting the values of positions 3 and 4, it returns a list containing those elements: ['b','b']

Experiment With Lists

# Here's a chance to play around with lists for a bit.
# Take a look at what the following code does and try to guess how it works.

print "EXAMPLE 1: Lists can contain strings"
string_list = ['HTML', 'CSS', 'Python']
print string_list

print "EXAMPLE 2: Lists can contain numbers"
number_list = [3.14159, 2.71828, 1.61803]
print number_list

print "EXAMPLE 3: Lists can be 'accessed' and 'sliced' like how we accessed and sliced strings in the previous lessons"
pi = number_list[0]
not_pi = number_list[1:]
print pi
print not_pi

print "EXAMPLE 4: Lists can contain strings AND numbers"
mixed_list = ['Hello!', 42, "Goodbye!"]
print mixed_list

print "Example 5: Lists can even contain other lists"
list_with_lists = [3, 'colors:', ['red', 'green', 'blue'], 'your favorite?']
print list_with_lists

Quiz - Stooges!

Define a variable STOOGES whose value is a list of the names of the three stooges.


Quiz - Days in a Month

Given the variable: days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
Define a procedure, how_many_days that takes a number as an input, and returns the number of days in that month.

def how_many_days(month):
return days_in_month[month - 1]

print how_many_days(1)
# >>> 31

print how_many_days(9)
# >>> 30

The reason the -1 is there, is because the elements in the list start at zero, not one, so by going -1, you shift everything over one, so it can display the correct response/value/list item.

Play with Nested Lists

# Every entry in the following list is itself a list
nested_list = [['HTML', 'Hypertext Markup Language forms the structure of webpages'],
['CSS' , 'Cascading Style Sheets give pages style'],
['Python', 'Python is a programming language'],
['Lists', 'Lists are a data structure that let you organize information']]

first_concept = nested_list[0]

print "What do you think this will print?"
print first_concept

print "Since first_concept was itself a list, we can access it's elements"
first_title = first_concept[0]
first_description = first_concept[1]

print "What will this print?"
print first_title
print first_description

Nested Lists

Lists are more flexible, since you can include strings and numbers, and lists within lists as well.

Here's an example of a nested list (lists within lists) that contains both strings and numbers:

mixed_up = ['apple', 3, 'oranges', 27,[1, 2, ['alpha', 'beta']]]

Here's a more practical use of a list of lists:

beatles = [['john', 1940], ['paul', 1942], ['george', 1943], ['ringo', 1940]]

And how to call data within:

print beatles[3]
>>> ['Ringo', 1940]
>>> This displays the list contents within a nest of lists.

To display the first value of the list within a list (as an example), you would format the syntax like this:

print beatles[3][0]
>>> Ringo

print beatles[3][1]
>>> 1940

Quiz - Countries

Given the variable countries defined as: (country name, capital, population in millions)

countries = [['China', 'Beijing', 1350], ['India', 'Delhi', 1210], ['Romania', 'Bucharest', 21], ['United States', 'Washington', 307]]

Write code to print out the capital of India.

# My Answer:

india_cap = countries[2][2]
print india_cap

# Test run = incorrect.

# My Revised Answer:

india_cap = countries[1][1]
print india_cap

# Instructor Answer:

print countries[1][1]

Quiz - Relative Size

Using the variable COUNTRIES from the previous quiz, what multiple of Romania's population is the population of China? (For those not good at math like myself, divide the pop of china by the pop of Romania)

My Answer:

print countries[0][2] / countries[2][2]

Test Run = 64


The two concepts you'll encounter are called mutation and aliasing. Understanding them will help you avoid hours of unnecessary frustration in the future.

Mutation: You can change the value of an item in a list after you have created that list. (Or multiple items)



(The p[0]='Y' replaces the H in Hello, but the list is not changed...)

Here's another example to help clear it up a bit:

print p
>>> ['H','e','l','l','o']
print p
>>> ['Y','e','l','l','o']
print p
>>> ['Y','e','l','l','!']

(The p[0]='Y' replaces the H in Hello, but the list is not changed...)

Quiz - Different Stooges

We defined stooges=['Moe','Larry','Curly'] but in some Stooges films, Curly was replaced by Shemp. Write one line of code that changes the value of stooges to be ['Moe','Larry','Shemp'] but does not create a new list object.

#My Answer:

print stooges

Yello Mutation

print p
>>> ['H','e','l','l','o']
>>> q is now p.
print q
>>> ['Y','e','l','l','!']

And some more fun with mutations:

p = ['H','e','l','l','o']
q = p
print p, q
>>> ['H','e','l','l','o'] ['H','e','l','l','o']
p[0] = 'Y'
print p
>>> ['Y','e','l','l','o']
print q
>>> ['Y','e','l','l','o']


Aliasing - using two different ways to refer to the same object. (Modifying the data through one name implicitly modifies the values associated with all aliased names)

>>> Both Q and P refer to ['James']
>>> If you make a change to P, it affects Q as well.
print q
>>> ['Janes']

# If you then did this:
# Then this happens:
print p
>>> [0,0,7]
print q
>>> ['Janes']
>>> Even though we changed P's value to something else, because Q still refers to the original value of P, that is stored and can be called as Q (until something changes).

Quiz - Secret Agent Man

What is the value of agent[2] after the following code is run:

spy = [0,0,7]
agent = spy

# My Answer: 8

And here is some more elaboration on that...

print spy,agent
>>> [0,0,7] [0,0,7]
print agent[2]
>>> 7
>>> The position 2 of spy is the position 2 of agent, plus 1.
print spy
>>> [0,0,8]
print spy[2]
>>> 8
print agent
>>> [0,0,8]
print agent[2]
>>> 8

Now try this for fun:

print spy
>>> [0,9,8]

Quiz - Replace Spy

Define a procedure REPLACE_SPY that takes a list of three numbers as its input, and modifies the value of the 3rd element in the input list to be one more than its previous value.

This is the behaviour that we want:

print spy
>>> [0,0,8]

My Answer:

def replace_spy(spy):
return spy[2]+1
print replace_spy

>>> 8
>>> This isn't correct. I need to return the list, not the one incremented value.

My Revised Answer:

def replace_spy(spy):
return spy

print (spy)

>>> [0,0,8]

Instructor Answer:

def replace_spy(p):

There is no return, because you don't need to return a value, since you actually changed the value in the list.

List Operations - Append

APPEND is a method. It lets you add a new element to the end of a list. This does not create a new list, it mutates an existing list.

The syntax is:


An example of this:


print stooges
>>> ['moe','larry','curly','shemp']

List Operations - Plus (+)

PLUS (+) is also an operator. It lets you produce a new list by combining two lists. This does not retain the original lists, this creates a NEW entity.

The syntax is:


Or more specifically:

>>> [0,2,2,3]

List Operations - Len

LEN is the last operator we'll learn about here (it's short for Length). It tells you how many elements are in the input.

The syntax is:


Here's an idea how to use it:

>>> 2

>>> 2

For the last example, it only counts the outer elements. Len can also be used against a string:

>>> 7

Quiz - Len Quiz

What is the value of LEN(p) after running this code:


My Answer: 5

Because... [1,2] is 2, append (3) makes the total 3, +[4,5] adds two more elements, for a total of 5.

Quiz - Append Quiz

What is the value of len(p) after running this code:


My Answer: 4 >>> wrong.

Instructor answer: 3

And the explanation:

p = 2, q = 2. Append adds the list to 1,2. This adds q as an object... a single object. The + operator adds the values of q, which is 2. The append is adding a reference to an object to p. So that is not seen as a list of 2 objects, but a single reference/object.

Loops On Lists

Loops are collections of things, and loops on lists can go through a list, and do something with every element in a list. Remember while loops?


When the <test> is true, it runs the codeblock. When it's false, the codeblock is no longer run, and therefore passed over.

Quiz - Loops on Lists

Define a procedure called print_all_elements that takes a list as an input, and print out every element in the list.

Most of the code is provided here:

def print_all_elements(p):
i = 0
print p [i]
i = i +1

The answer is:

i <= len(p) -1

'For' Loops

Python provides a simpler way to loop through items in a list compared to while loops, this is using 'for loops'. For each element in the list, we assign that element to a name, and evaluate the block.

The syntax is:

for <name> in <list>:

And here's an example of the use, in some detail:

def print_all_elements(p):
for e in p:
print e

mylist = [1,2,[3,4]]

So what will the output be? For the first iteration of the loop, 'e' will be assigned to the first value in the list. In this case, '1'. So the loop will print '1'. On the second iteration of the loop, it will assign the name of 'e' to the second value in the list, which is '2'... and print that. Now for the third iteration of the loop, it will assign the name of 'e' to the third element in the list, which is a list... [3,4]... so it would print the list to the console.

Play With For Loops

# Read through these examples and try to figure out what's going on.
# Press "Test Run" to see what they do.

print "EXAMPLE 1: We can use for loops to go through a list of strings"
example_list_1 = ['a', 'b', 'c', 'd']
for thing in example_list_1:
print thing

print "EXAMPLE 2: We can use for loops on nested lists too!"
example_list_2 = [['China', 'Beijing'],
['USA' , 'Washington D.C.'],
['India', 'Delhi']]
for country_with_capital in example_list_2:
country = country_with_capital[0]
capital = country_with_capital[1]
print capital + ' is the capital of ' + country

Quiz - Sum List

Define a procedure SUM_LIST that takes a list of numbers as its input, and outputs a sum of all the elements in the input list.

For example: sum_list([1,7,4]) >>> 12

#print sum_list([1, 7, 4])
#>>> 12

#print sum_list([9, 4, 10])
#>>> 23

#print sum_list([44, 14, 76])
#>>> 134

And now, the answer:

def sum_list(p):
result = 0
for e in p:
result = result + e
return result

Quiz - Measure Udacity

Define a procedure measure_udacity that takes a list of strings as an input, and outputs a number that is the total number of elements in that list that start with an uppercase U.

Some examples:

measure_udacity(['Dave','Sebastian','Katy']) >>> 0
measure_udacity(['Umiko','Umberto']) >>> 2


def measure_udacity(U):
count = 0
for e in U:
if e[0] == 'U':
count = count + 1
return count

print measure_udacity(['Dave','Sebastian','Katy'])
>>> 0
print measure_udacity(['Umika','Umberto'])

Quiz - Find Element

Define a procedure find_element that takes a list and a value of any type as an input, and outputs the index of the first element in the input list that matches the value.

An example:

find_element([1,2,3],3) >>> Output will be 2. (Since it found a match for the value 3, and it is in position 2 in the list)
find_element(['alpha','beta'],'gamma') >>> Output will be -1 (Since no match is found)

Answer (Solution 1 - While loop):

def find_element(p,t):
while i<len(p):
if p[i]==t:
return i
i = i+1
return -1

Answer (Solution 2 - For loop):

def find_element(p,t):
for e in p:
if e == t:
return i
return -1


There's a built-in list operation called INDEX, it's invoked on a list where you input (pass in) a value, and the output is the position of that input in the list. If there is no match, we get an error, instead of -1.

The syntax is:


A practical example of this is:

p = [0,1,2]
print p.index(2)
>>> 2

Or this:

print p.index(2)
>>> 2

The reason we just get 2 as a result, is it displays the position of the first matching element, any other matches will not be displayed. So in this example, the first match of '2' is in position 2 of the list.

And if there is no match:

print p.index(3)
>>> 3 is not in list

As far as errors go, that's a pretty understandable and graceful message.

List Operator - 'in'

There's one more built-in list operation called IN. It returns either a True or False, instead of a position in the list.

The syntax is:

<value> in <list>

A practical example:

print 3 in p
>>> False

List Operator - 'not in'

There's a variation to in... which would be not in.

The syntax is:

<value> not in <list>

And now for a practical example:

print not 3 in p
>>> True (because 3 is not in the list, and that statement is therefore true)

Quiz - Index (IN, Not IN)

Define find_element using index.


def find_element(p,t):
if t in p:
return p.index(t)
return -1


def find_element(p,t):
if t not in p:
return -1
return p.index(t)