Lists, Strings, and Mutability

>>> sample_list[3]
'Eric'
>>> print(sample_list)
['Graham', 'John', 'Terry', 'Eric', 'Terry', 'Michael']
>>> sample_string[8] = 'f'

Traceback (most recent call last):
  File "", line 1, in 
    sample_string[8] = 'f'
TypeError: 'str' object does not support item assignment
>>> 
>>> name = "Old Woman"
>>> person = name
>>> name = "Dennis"
>>> print(name)
Dennis
>>> print(person)
Old Woman
>>> dish = ["Spam", "Spam", "Spam", "Spam", "Spam", "Spam", "baked beans", "Spam", "Spam", "Spam", "Spam"]
>>> mr_buns_order = dish
>>> print(dish)
['Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'baked beans', 'Spam', 'Spam', 'Spam', 'Spam']
>>> print(mr_buns_order)
['Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'baked beans', 'Spam', 'Spam', 'Spam', 'Spam']
>>> dish[6] = "Spam"
>>> print(mr_buns_order)
['Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam']
>>> print(dish)
['Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam']

Working with Lists
len(some_list)
max(some_list)

>>> batch_sizes = [15, 6, 89, 34, 65, 35]
>>> max(batch_sizes)
89
>>> python_vareties = ['Burmese Python', 'African Rock Python', 'Ball Python', 'Reticulated Python', 'Angolan Python']
>>> max(python_varieties)

Traceback (most recent call last):
  File "", line 1, in 
    max(python_varieties)
NameError: name 'python_varieties' is not defined
>>> max(python_vareties)
'Reticulated Python'

sorted

>>> sorted(batch_sizes)
[6, 15, 34, 35, 65, 89]
>>> sorted(batch_sizes, reverse=True)
[89, 65, 35, 34, 15, 6]
>>> print(batch_sizes)
[15, 6, 89, 34, 65, 35]

List

>>> python_versions = [1.0, 1.5, 1.6, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 3.0, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6]
>>> python_versions[0]
1.0
>>> python_versions[1]
1.5
>>> python_versions[7]
2.4
>>> python_versions[-1]
3.6

Error

>>> my_list = ['a','b','c','d','e']
>>> my_list[4]
'e'
>>> my_list[5]

Traceback (most recent call last):
  File "", line 1, in 
    my_list[5]
IndexError: list index out of range
def how_many_days(month_number):
    days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
    return days_in_month[month_number-1]
    
print(how_many_days(8))

slice

>>> months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
>>> q3 = months[6:9]
>>> print(q3)
['July', 'August', 'September']
>>> print(months)
['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
eclipse_dates = ['June 21, 2001', 'December 4, 2002', 'November 23, 2003',
                 'March 29, 2006', 'August 1, 2008', 'July 22, 2009',
                 'July 11, 2010', 'November 13, 2012', 'March 20, 2015',
                 'March 9, 2016']
                 
last_eclipse= eclipse_dates[-3:]                 
print(last_eclipse)
>>> sample_string = "And Now For Something Completely Different"
>>> sample_list = ['Graham', 'John', 'Terry', 'Eric', 'Terry', 'Michael']
>>> sample_string[4]
'N'
>>> sample_list[4]
'Terry'
>>> sample_string[12:21]
'Something'
>>> sample_list[2:4]
['Terry', 'Eric']
>>> len(sample_string)
42
>>> len(sample_list)
6
>>> 'thing' in sample_string
True
>>> 'Rowan' in sample_list
False

Branches -2

def punctuate(sentence, phrase_type):
	if phrase_type == "exclamation":
		sentence_punct = sentence + "!"
	elif phrase_type == "question":
		sentence_punct = sentence + "?"
	elif phrase_type == "aside":
		sentence_punct = "(" + sentence + ".)"
	else:
		sentence_punct = sentence + "."
	return sentence_punct
def cylinder_surface_area(radius, height, has_top_and_bottom):
	side_area = height * 6.28 * radius
	if has_top_and_bottom:
		top_area = 3.14 * radius ** 2
		return top_area + side_area
	else:
		return side_area
errors = 3
if errors:
	print("There are " + errors + " mistakes. Please correct.")
else:
	print("No mistakes here!")
def convert_to_numeric(score):
    """
    Convert the score to a numerical type.
    """
    converted_score = float(score)
    return converted_score

def sum_of_middle_three(score1,score2,score3,score4,score5):
    """
    Find the sum of the middle three numbers out of the five given.
    """
    max_score = max(score1,score2,score3,score4,score5)
    min_score = min(score1,score2,score3,score4,score5)
    sum = score1 + score2 + score3 + score4 + score5 - max_score - min_score
    return sum

def score_to_rating_string(score):
    if score < 1:
    	return "Terrible"
    elif score < 2:
    	return "Bad"
    elif score < 3:
    	return "OK"
    elif score < 4:
    	return "Good"
    elif score <= 5:
    	return "Excellent"
    else:
    	return "nothing"

def scores_to_rating(score1,score2,score3,score4,score5):

    score1 = convert_to_numeric(score1)
    score2 = convert_to_numeric(score2)
    score3 = convert_to_numeric(score3)
    score4 = convert_to_numeric(score4)
    score5 = convert_to_numeric(score5)

    #STEP 2 and STEP 3 find the average of the middle three scores
    average_score =     
        sum_of_middle_three(score1,score2,score3,score4,score5)/3

    #STEP 4 turn average score into a rating
    rating = score_to_rating_string(average_score)

    return rating

Code with Branches

point = 189
prize = "No prize"

if point <= 50:
    prize = "wooden rabbit"
elif 51 <= point <= 150:
    prize = "No prize"
elif 151 <= point <= 180:
    prize = "wafer-thin mint"
elif 181 <= point <= 200:
    prize = "penguin"
    
if prize == "No prize":
    print("oh dear, no prize this time")
else:
    print("Congratulations! You have won a " + prize + "!" ) 

keywords like and, or and not

if is_raining and is_sunny:
	print("Is there a rainbow?")

if (not do_not_emai) and (location == "USA" or location == "CAN"):
	send_email()

branches

if 18.5 <= weight_in_kg / (height_in_m)**2 < 25:
	print("BMI is considered 'normal'.")
&#91;/python&#93;

&#91;python&#93;
if numer % 2 == 0:
	print("The number " + str(number) + " is even.")
else:
	print("The number " + str(number) + " is odd.")
&#91;/python&#93;

&#91;python&#93;
def garden_calendar(season):
	if season == "spring":
		print("time to plant the garden!")
	elif season == "summer":
		print("time to water the garden!")
	elif season == "autumn" or season == "fall":
		print("time to harvest the garden!")
	elif season == "winter":
		print("time to stay indoors and drink tea!")
	elif:
		print("I don't recognize that season")
&#91;/python&#93;

&#91;python&#93;
phone_balance = 7.62
bank_balance = 104.39

if phone_balance < 10:
	phone_balance += 10
	bank_balance -= 10
print(phone_balance)
print(bank_balance)

number = 145346334
if number % 2 == 0:
	print("The number " + str(number) + " is even.")
else:
	print("The number " + str(number) + " is odd.")

age = 35

free_up_to_age = 4
child_up_to_age = 18
senior_from_age = 65

concession_ticket = 1.25
adult_ticket = 2.50

if age <= free_up_to_age:
	ticket_price = 0
elif age <= child_up_to_age:
	ticket_price = concession_ticket
elif age >= senior_from_age:
	ticket_price = concession_ticket
else:
	ticket_price = adult_ticket

message = "somebody who is {} years old will pay ${} to ride the bus.".format(age,ticket_price)
print(message)

function

>>> def cylinder_volume(height, radius):
	pi = 3.14159
	return height * pi * radius ** 2

>>> cylinder_volume(10, 3)
282.7431
def population_density(population, land_area):
    return population / land_area

test1 = population_density(10, 1)
expected_result1 = 10
print("expected result: {}, actual result: {}".format(expected_result1, test1))

test2 = population_density(864816, 121.4)
expected_result2 = 7123.6902801
print("expected result: {}..., actual result: {}".format(expected_result2, test2))
def readable_timedelta(days):
    week = days / 7
    day = days % 7
    return "{} week(s) and {} day(s)".format(week, day)
    
print(readable_timedelta(120))

Type and Type conversion

>>> print(type(633))

>>> print(type("633"))

>>> print(type(633.0))

mon_sales = 121
tues_sales = 105
wed_sales = 110
thurs_sales = 98
fri_sales = 95
total = str(mon_sales + tues_sales + wed_sales + thurs_sales + fri_sales)
print("This week\'s total sales: " + total)

python string method
https://docs.python.org/3/library/stdtypes.html#string-methods

prophecy = "And there shall in that time be rumours of things going astray, and there will be a great confusion as to where things really are, and nobody will really know where lieth those little things with the sort of raffia work base, that has an attachment…at this time, a friend shall lose his friends’s hammer and the young shall not know where lieth the things possessed by their fathers that their fathers put there only just the night before around eight o’clock…"

vowel_count = 0
vowel_count += prophecy.count('a')
vowel_count += prophecy.count('A')
vowel_count += prophecy.count('e')
vowel_count += prophecy.count('E')
vowel_count += prophecy.count('i')
vowel_count += prophecy.count('I')
vowel_count += prophecy.count('o')
vowel_count += prophecy.count('O')
vowel_count += prophecy.count('u')
vowel_count += prophecy.count('U')

print(vowel_count)

format

log_message = "IP address {} accessed {} at {}".format(user_ip, url, now)

city = "Seoul"
high_temperature = 18
low_temperature = 9
temperature_unit = "degrees Celsius"
weather_conditions = "light rain"

alert = "Today's forecast for {}: The temperature will range from {} to {}{}. Conditions will be {}.".format(city, high_temperature, low_temperature, temperature_unit, weather_conditions)
# print the alert
print(alert)

Changing Variable

>>> manila_pop = 1780148
>>> manila_area = 16.56
>>> manila_pop_density = manila_pop/manila_area
>>> print(int(manila_pop_density))
107496

bool

>>> 1 < 2
True
>>> 42 > 43
False
sf_population, sf_area = 864816, 231.89
rio_population, rio_area = 6453682, 486.5

san_francisco_pop_density = sf_population/sf_area
rio_de_janeiro_pop_density = rio_population/rio_area

print(san_francisco_pop_density > rio_de_janeiro_pop_density)

string

>>> print("hello")
hello
>>> print('hello')
hello
>>> welcome_message = "Hello, welcome to Tokyo"
>>> print(welcome_message)
Hello, welcome to Tokyo
>>> instructor_1 = "Philip"
>>> instructor_2 = "Charlie"
>>> print(instructor_1 + " and " + instructor_2)
Philip and Charlie
messiah = 'He\'s not the Messiah, he\'s a very naughty boy!'
print(messiah)

username = "Kinari"
timestamp = "04:50"
url = "http://petshop.com/pets/mammals/cats"
print(username + " accessed the site " + url + " at " + timestamp)

len

>>> tokyo_length = len("Tokyo")
>>> print(tokyo_length)
5

given_name = "Charlotte"
middle_names = "Hippopotamus"
family_name = "Turner"

name_length = len(given_name+middle_names+family_name)

driving_licence_character_limit = 28
print(name_length <= driving_licence_character_limit) [/python]

Arithmetic

Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> print(3+1)
4
>>> 3 + 1
4
>>> print(1 + 2 + 3 * 3)
12
>>> print((1 + 2 + 3) * 3)
18
>>> print(3**2)
9
>>> print(9 % 2)
1
>>> print(15 // 4)
3
>>> print(16 // 4)
4
>>> print(-5 // 4)
-2
>>> print((23 + 32 + 64)/ 3)
39

integer and floats

>>> print(3/4)
0
>>> print(16/4)
4
>>> 3 + 2.5
5.5
>>> 213.13
213.13
>>> 341.
341.0
>>> int(49.7)
49
>>> int(16/4)
4
>>> float(3520+3239)
6759.0
>>> print(0.1)
0.1
>>> print(0.1 + 0.1 + 0.1)
0.3

float e.g.
Length of a fish you caught, in metres
Length of time it took to catch the first fish, in hours

4.445e8 is equal to 4.445 * 10 ** 8 which is equal to 444500000.0.

# The current volume of a water reservoir (in cubic metres)
reservoir_volume = 4.445e8
# The amount of rainfall from a storm (in cubic metres)
rainfall = 5e6

# decrease the rainfall variable by 10% to account for runoff
rainfall *= 0.9
# add the rainfall variable to the reservoir_volume variable
reservoir_volume += rainfall
# increase reservoir_volume by 5% to account for stormwater that flows
reservoir_volume *= 1.05 
# into the reservoir in the days following the storm

# decrease reservoir_volume by 5% to account for evaporation
reservoir_volume *= 0.95
# subtract 2.5e5 cubic metres from reservoir_volume to account for water
# that's piped to arid regions.
reservoir_volume -= 2.5e5
# print the new value of the reservoir_volume variable
print(reservoir_volume)

Panoramic Video Texture

1. Review Video Textures and panoramas
2. Combine Video Textures and panoramas to form panoramic video textures
3. Construct a panorama from video

a video that has been stitched into a single, wide field of view
Video registration
video textures of dynamic regions

map a continuous diagonal slice of the input video volume to the output panorama
restricts boundaries to frames
shears spatial structures across time