Introduction To Python
Introduction To Python
Finish the code that creates the areas list. Build the list so that the list
"I said " + ("Hey " * 2) + "Hey!"
first contains the name of each room as a string and then its area. In
other words, add the strings "hallway", "kitchen" and "bedroom" at
the appropriate locations.
"The correct answer to this multiple choice exercise is answer number " + Print areas again; is the printout more informative this time?
2
# area variables (in square meters)
hall = 11.25
True + False
kit = 18.0
Create a list liv = 20.0
bed = 10.75
bath = 9.50 Print out the type of house. Are you still dealing with a list?
Print out the second element from the areas list (it has the
C value 11.25).
Subset and print out the last element of areas, being 9.50. Using a
List of lists negative index makes sense here!
Select the number representing the area of the living room (20.0) and
Finish the list of lists so that it also contains the bedroom and print it out.
bathroom data. Make sure you enter these in order!
Print out house; does this way of structuring your data make more
sense? # Create the areas list
areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", # Create the areas list
10.75, "bathroom", 9.50] areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom",
# Print out second element from areas 10.75, "bathroom", 9.50]
print(areas[1]) # Use slicing to create downstairs
# Print out last element from areas downstairs = areas[0:6]
print(areas[-1]) # Use slicing to create upstairs
# Print out the area of the living room upstairs = areas[6:10]
print(areas[5]) # Print out downstairs and upstairs
print(downstairs)
Subset and calculate
print(upstairs)
Using a combination of list subsetting and variable assignment, create
a new variable, eat_sleep_area, that contains the sum of the area of Slicing and dicing (2)
the kitchen and the area of the bedroom.
Print the new variable eat_sleep_area. Create downstairs again, as the first 6 elements of areas. This time,
simplify the slicing by omitting the begin index.
Create upstairs again, as the last 4 elements of areas. This time,
# Create the areas list
simplify the slicing by omitting the end index.
areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom",
10.75, "bathroom", 9.50] # Create the areas list
# Sum of kitchen and bedroom area: eat_sleep_area areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom",
eat_sleep_area = areas[3] + areas[-3] 10.75, "bathroom", 9.50]
# Print the variable eat_sleep_area # Alternative slicing to create downstairs
print(eat_sleep_area) downstairs = areas[:6]
# Alternative slicing to create upstairs
Slicing and dicing
upstairs = areas[6:]
Use slicing to create a list, downstairs, that contains the first 6
elements of areas. Subsetting lists of lists
Do a similar thing to create a new variable, upstairs, that contains the Try out the commands in the following code sample in the IPython Shell:
last 4 elements of areas.
Print both downstairs and upstairs using print().
x = [["a", "b", "c"], areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom",
10.75, "bathroom", 9.50]
["d", "e", "f"],
# Correct the bathroom area
["g", "h", "i"]]
areas[-1] = 10.50
x[2][0]
# Change "living room" to "chill zone"
x[2][:2]
areas[4] = "chill zone"
x[2] results in a list, that you can subset again by adding additional square
brackets. Extend a list
What will house[-1][1] return? house, the list of lists that you created before,
is already defined for you in the workspace. You can experiment with it in Use the + operator to paste the list ["poolhouse", 24.5] to the end of
the IPython Shell. the areas list. Store the resulting list as areas_1.
Further extend areas_1 by adding data on your garage. Add the
string "garage" and float 15.45. Name the resulting list areas_2.
A float: the kitchen area
# Create the areas list (updated version)
areas = ["hallway", 11.25, "kitchen", 18.0, "chill zone", 20.0,
A string: "kitchen"
"bedroom", 10.75, "bathroom", 10.50]
# Add poolhouse data to areas, new list is areas_1
A float: the bathroom area areas_1 = areas + ["poolhouse", 24.5]
# Add garage data to areas_1, new list is areas_2
Update the area of the bathroom area to be 10.50 square meters areas = ["hallway", 11.25, "kitchen", 18.0,
instead of 9.50. "chill zone", 20.0, "bedroom", 10.75,
Make the areas list more trendy! Change "living room" to "chill
zone". "bathroom", 10.50, "poolhouse", 24.5,
"garage", 15.45]
# Create the areas list
Which of the code chunks will do the job for us?
var1 = [1, 2, 3, 4]
del(areas[10]); del(areas[11]) var2 = True
# Print out type of var1
del(areas[10:11]) print(type(var1))
# Print out length of var1
print(len(var1))
del(areas[-4:-2])
# Convert var2 to an integer: out2
out2 = int(var2)
del(areas[-3]); del(areas[-4])
Help!
Inner workings of lists
help(max)
# Create list areas ?max
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
Use the IPython Shell to open up the documentation on pow(). Which of the
# Create areas_copy following statements is true?
areas_copy = list(areas)
# Change areas_copy pow() takes three arguments: base, exp, and mod. If you don’t
areas_copy[0] = 5.0 specify mod, the function will return an error.
# Print areas
print(areas) pow() takes three arguments: base, exp, and None. All of these arguments
are required.
Familiar functions
Use print() in combination with type() to print out the type of var1.
Use len() to get the length of the list var1. Wrap it in a print() call to pow() takes three arguments: base, exp, and mod. base and exp are
directly print it out. required arguments, mod is an optional argument.
Use int() to convert var2 to an integer. Store the output as out2.
# Create variables var1 and var2 pow() takes two arguments: exp and mod. If you don’t specify exp, the
function will return an error.
Multiple arguments # Print out place and place_up
Use + to merge the contents of first and second into a new list: full. print(place)
Call sorted() on full and specify the reverse argument to be True. Save print(place_up)
the sorted list as full_sorted.
Finish off by printing out full_sorted. # Print out the number of o's in place
print(place.count('o'))
# Create lists first and second
List Methods
first = [11.25, 18.0, 20.0]
second = [10.75, 9.50] Use the index() method to get the index of the element in areas that is
# Paste together first and second: full equal to 20.0. Print out this index.
Call count() on areas to find out how many times 9.50 appears in the
full = first + second list. Again, simply print out this number.
# Sort full in descending order: full_sorted
full_sorted = sorted(full, reverse=True) # Create list areas
# Print out full_sorted areas = [11.25, 18.0, 20.0, 10.75, 9.50]
print(full_sorted) # Print out the index of the element 20.0
print(areas.index(20.0))
String Methods # Print out how often 9.50 appears in areas
Use the upper() method on place and store the result in place_up. Use print(areas.count(9.50))
the syntax for calling methods that you learned in the previous video.
Print out place and place_up. Did both change? List Methods (2)
Print out the number of o’s on the variable place by
calling count() on place and passing the letter 'o' as an input to the Use append() twice to add the size of the poolhouse and the garage
method. We’re talking about the variable place, not the word "place"! again: 24.5 and 15.45, respectively. Make sure to add them in this
order.
# string to experiment with: place Print out areas
Use the reverse() method to reverse the order of the elements in areas.
place = "poolhouse" Print out areas once more.
# Use upper() on place: place_up
place_up = place.upper() # Create list areas
areas = [11.25, 18.0, 20.0, 10.75, 9.50] print("Circumference: " + str(C))
# Use append twice to add poolhouse and garage size print("Area: " + str(A))
areas.append(24.5)
Selective import
areas.append(15.45)
# Print out areas Perform a selective import from the math package where you only
import the radians function.
print(areas)
Calculate the distance travelled by the Moon over 12 degrees of its
# Reverse the orders of the elements in areas orbit. Assign the result to dist. You can calculate this as \r * phi,
areas.reverse() where r is the radius and phi is the angle in radians. To convert an
angle in degrees to an angle in radians, use the radians() function,
# Print out areas which you just imported.
print(areas) Print out dist.
# edited/added
fifa = pd.read_csv('fifa.csv', skipinitialspace=True, usecols=['position',
'height'])
positions = list(fifa.position)
heights = list(fifa.height)
# heights and positions are available as lists
# Import numpyimport numpy as np
# Convert positions and heights to numpy arrays: np_positions, np_heights
np_positions = np.array(positions)
np_heights = np.array(heights)
# Heights of the goalkeepers: gk_heights
gk_heights = np_heights[np_positions == 'GK']
# Heights of the other players: other_heights
other_heights = np_heights[np_positions != 'GK']
# Print out the median height of goalkeepers. Replace 'None'
print("Median height of goalkeepers: " + str(np.median(gk_heights)))