Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
31 views

Introduction To Python

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Introduction To Python

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

INTRODUCTION TO PYTHON print(5 + 5)

# Example, do not modify! print(5 - 5)


print(5 / 8) # Multiplication, division, modulo, and exponentiation
# Put code below here print(3 * 5)
print(7 + 10) print(10 / 2)
print(18 % 7)
When to use Python?
print(4 ** 2)
Python is a pretty versatile language. For which applications can you use
Python? # Calculate two to the power of five
print(2 ** 5)

You want to do some quick calculations. Variable Assignment

 Create a variable savings with the value 100.


For your new business, you want to develop a database-driven website.  Check out this variable by typing print(savings) in the script.

# Create a variable savings


Your boss asks you to clean and analyze the results of the latest savings = 100
satisfaction survey.
# Print out savings
print(savings)
All of the above.
Calculations with variables
Any comments?
 Create a variable growth_multiplier, equal to 1.1.
 Change the values of the numbers shown to see how Python performs  Create a variable, result, equal to the amount of money you saved
addition and subtraction. after 7 years.
 Change the values of the numbers shown to see how multiplication,  Print out the value of result.
division, modulo, and exponentiation works in Python.
 Calculate and print 2 to the power of 5. # Create a variable savings
savings = 100
# Addition, subtraction
# Create a variable growth_multiplier  Calculate the product of savings and growth_multiplier. Store the
result in year1.
growth_multiplier = 1.1  What do you think the resulting type will be? Find out by printing out
# Calculate result the type of year1.
 Calculate the sum of desc and desc and store the result in a new
result = savings * growth_multiplier ** 7 variable doubledesc.
# Print out result  Print out doubledesc. Did you expect this?
print(result)
savings = 100
Other variable types growth_multiplier = 1.1
In the previous exercise, you worked with two Python data types: desc = "compound interest"
# Assign product of savings and growth_multiplier to year1
 int, or integer: a number without a fractional part. savings, with the
value 100, is an example of an integer. year1 = savings * growth_multiplier
 float, or floating point: a number that has both an integer and # Print the type of year1
fractional part, separated by a point. growth_multiplier, with the
value 1.1, is an example of a float. print(type(year1))
# Assign sum of desc and desc to doubledesc
Next to numerical data types, there are two other very common data types:
doubledesc = desc + desc
 str, or string: a type to represent text. You can use single or double # Print out doubledesc
quotes to build a string.
print(doubledesc)
 bool, or boolean: a type to represent logical values. Can only
be True or False (the capitalization is important!).
Type conversion
 Create a new string, desc, with the value "compound interest".
 Create a new boolean, profitable, with the value True.  Hit Run Code to run the code. Try to understand the error message.
 Fix the code such that the printout runs without errors; use the
function str() to convert the variables to strings.
# Create a variable desc  Convert the variable pi_string to a float and store this float as a new
desc = "compound interest" variable, pi_float.
# Create a variable profitable
# Definition of savings and result
profitable = True
savings = 100
Operations with other types
result = 100 * 1.10 ** 7  Create a list, areas, that contains the area of the hallway (hall), kitchen
(kit), living room (liv), bedroom (bed) and bathroom (bath), in this
# Fix the printout order. Use the predefined variables.
print("I started with $" + str(savings) + " and now have $" + str(result) + ".  Print areas with the print() function.
Awesome!")
# Definition of pi_string # Area variables (in square meters)
pi_string = "3.1415926" hall = 11.25
# Convert pi_string into float: pi_float kit = 18.0
pi_float = float(pi_string) liv = 20.0
bed = 10.75
Can Python handle everything? bath = 9.50
Now that you know something more about combining different sources of # Create list areas
information, have a look at the four Python expressions below. Which one of
these will throw an error? You can always copy and paste this code in the areas = [hall, kit, liv, bed, bath]
IPython Shell to find out! # Print areas
print(areas)
"I can add integers, like " + str(5) + " to strings."
Create list with different types

 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?

# Adapt list areas


# area variables (in square meters)
areas = ["hallway", hall, "kitchen", kit, "living room", liv, "bedroom", bed,
"bathroom", bath] hall = 11.25

# Print areas kit = 18.0

print(areas) liv = 20.0


bed = 10.75
Select the valid list bath = 9.50
my_list = [el1, el2, el3] # house information as list of lists
house = [["hallway", hall],
Can you tell which ones of the following lines of Python code are valid ways
to build a list? ["kitchen", kit],
A. [1, 3, 4, 2] B. [[1, 2, 3], [4, 5, 7]] C. [1 + 2, "a" * 5, 3] ["living room", liv],
["bedroom", bed],
A, B and C ["bathroom", bath]]
# Print out house
print(house)
B
# Print out the type of house
print(type(house))
B and C
Subset and conquer

 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

A string: "bathroom" areas_2 = areas_1 + ["garage", 15.45]

Replace list elements Delete list elements

 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.

Import package # Definition of radius


script. Fill in the code to calculate C and A and see how the print() functions r = 192500
create some nice printouts. # Import radians function of math packagefrom math import radians
 Import the math package. Now you can access the # Travel distance of Moon over 12 degrees. Store in dist.
constant pi with math.pi. dist = r * radians(12)
 Calculate the circumference of the circle and store it in C.
 Calculate the area of the circle and store it in A. # Print out dist
print(dist)
# Definition of radius
Different ways of importing
r = 0.43
# Import the math packageimport math my_inv([[1,2], [3,4]])
# Calculate C
 Import the numpy package as np, so that you can refer
C = 2 * r * math.pi
to numpy with np.
# Calculate A  Use np.array() to create a numpy array from baseball. Name this
A = math.pi * r ** 2 array np_baseball.
 Print out the type of np_baseball to check that you got it right.
# Build printout
# Create list baseball # Convert np_height_in to m: np_height_m
baseball = [180, 215, 210, 210, 188, 176, 209, 200] np_height_m = np_height_in * 0.0254
# Import the numpy package as npimport numpy as np # Print np_height_m
# Create a NumPy array from baseball: np_baseball print(np_height_m)
np_baseball = np.array(baseball)
Baseball player’s BMI
# Print out type of np_baseball
print(type(np_baseball))  Create a numpy array from the weight_lb list with the correct units.
Multiply by 0.453592 to go from pounds to kilograms. Store the
Baseball players’ height resulting numpy array as np_weight_kg.
 Use np_height_m and np_weight_kg to calculate the BMI of each
 Create a numpy array from height_in. Name this new player. Use the following equation: $ = $ Save the
array np_height_in. resulting numpy array as bmi.
 Print np_height_in.  Print out bmi.
 Multiply np_height_in with 0.0254 to convert all height
measurements from inches to meters. Store the new values in a new # edited/added
array, np_height_m.
weight_lb = mlb['Weight'].tolist()
 Print out np_height_m and check if the output makes sense.
# height_in and weight_lb are available as regular lists
# edited/addedimport pandas as pd # Import numpyimport numpy as np
mlb = pd.read_csv('baseball.csv') # Create array from height_in with metric units: np_height_m
# height_in is available as a regular list np_height_m = np.array(height_in) * 0.0254
height_in = mlb['Height'].tolist() # Create array from weight_lb with metric units: np_weight_kg
# height_in is available as a regular list np_weight_kg = np.array(weight_lb) * 0.453592
# Import numpyimport numpy as np # Calculate the BMI: bmi
# Create a numpy array from height_in: np_height_in bmi = np_weight_kg / np_height_m ** 2
np_height_in = np.array(height_in) # Print out bmi
# Print out np_height_in print(bmi)
print(np_height_in)
Lightweight baseball players
 Create a boolean numpy array: the element of the array should
be True if the corresponding baseball player’s BMI is below 21. You
np.array([1, 1, 2]) + np.array([3, 4, -1])
can use the < operator for this. Name the array light.
 Print the array light.
 Print out a numpy array with the BMIs of all baseball players whose
BMI is below 21. Use light inside square brackets to do a selection on np.array([0, 1, 2, 3, 4, 5])
the bmi array.
Subsetting NumPy Arrays
# height_in and weight_lb are available as a regular lists
 Subset np_weight_lb by printing out the element at index 50.
# Import numpyimport numpy as np  Print out a sub-array of np_height_in that contains the elements at
# Calculate the BMI: bmi index 100 up to and including index 110.

np_height_m = np.array(height_in) * 0.0254


# height_in and weight_lb are available as a regular lists
np_weight_kg = np.array(weight_lb) * 0.453592
# Import numpyimport numpy as np
bmi = np_weight_kg / np_height_m ** 2
# Store weight and height lists as numpy arrays
# Create the light array
np_weight_lb = np.array(weight_lb)
light = bmi < 21
np_height_in = np.array(height_in)
# Print out light
# Print out the weight at index 50
print(light)
print(np_weight_lb[50])
# Print out BMIs of all baseball players whose BMI is below 21
# Print out sub-array of np_height_in: index 100 up to and including index
print(bmi[light]) 110
print(np_height_in[100:111])
NumPy Side Effects

np.array([True, 1, 2]) + np.array([3, 4, False]) Your First 2D NumPy Array

 Use np.array() to create a 2D numpy array from baseball. Name


it np_baseball.
np.array([True, 1, 2, 3, 4, False])
 Print out the type of np_baseball.
 Print out the shape attribute of np_baseball. Use np_baseball.shape.

np.array([4, 3, 0]) + np.array([0, 2, 2])


# Create baseball, a list of lists
baseball = [[180, 78.4],  Make a new variable, np_weight_lb, containing the entire second
column of np_baseball.
[215, 102.7],  Select the height (first column) of the 124th baseball player
[210, 98.5], in np_baseball and print it out.
[188, 75.2]]
# edited/added
# Import numpyimport numpy as np
baseball = pd.read_csv('baseball.csv')[['Height', 'Weight']]
# Create a 2D numpy array from baseball: np_baseball
# baseball is available as a regular list of lists
np_baseball = np.array(baseball)
# Import numpy packageimport numpy as np
# Print out the type of np_baseball
# Create np_baseball (2 cols)
print(type(np_baseball))
np_baseball = np.array(baseball)
# Print out the shape of np_baseball
# Print out the 50th row of np_baseball
print(np_baseball.shape)
print(np_baseball[49,:])
Baseball data in 2D form # Select the entire second column of np_baseball: np_weight_lb
np_weight_lb = np_baseball[:,1]
 Use np.array() to create a 2D numpy array from baseball. Name
it np_baseball. # Print out height of 124th player
 Print out the shape attribute of np_baseball. print(np_baseball[123, 0])

# baseball is available as a regular list of lists 2D Arithmetic


# Import numpy packageimport numpy as np
 You managed to get hold of the changes in height, weight and age of
# Create a 2D numpy array from baseball: np_baseball all baseball players. It is available as a 2D numpy array, updated.
np_baseball = np.array(baseball) Add np_baseball and updated and print out the result.
 You want to convert the units of height and weight to metric (meters
# Print out the shape of np_baseball and kilograms, respectively). As a first step, create a numpy array
print(np_baseball.shape) with three values: 0.0254, 0.453592 and 1. Name this
array conversion.
Subsetting 2D NumPy Arrays  Multiply np_baseball with conversion and print out the result.

 Print out the 50th row of np_baseball. # edited/added


baseball = pd.read_csv('baseball.csv')[['Height', 'Weight', 'Age']] # Print out the median of np_height_in
n = len(baseball) print(np.median(np_height_in))
updated = np.array(pd.read_csv('update.csv', header = None))
Explore the baseball data
# baseball is available as a regular list of lists# updated is available as 2D
numpy array  The code to print out the mean height is already included. Complete
# Import numpy packageimport numpy as np the code for the median height. Replace None with the correct code.
 Use np.std() on the first column of np_baseball to calculate stddev.
# Create np_baseball (3 cols)
Replace None with the correct code.
np_baseball = np.array(baseball)  Do big players tend to be heavier? Use np.corrcoef() to store the
# Print out addition of np_baseball and updated correlation between the first and second column
of np_baseball in corr. Replace None with the correct code.
print(np_baseball + updated)
# Create numpy array: conversion # np_baseball is available
conversion = np.array([0.0254, 0.453592, 1]) # Import numpyimport numpy as np
# Print out product of np_baseball and conversion # Print mean height (first column)
print(np_baseball * conversion) avg = np.mean(np_baseball[:,0])
print("Average: " + str(avg))
Average versus median
# Print median height. Replace 'None'
 Create numpy array np_height_in that is equal to first column med = np.median(np_baseball[:,0])
of np_baseball.
 Print out the mean of np_height_in. print("Median: " + str(med))
 Print out the median of np_height_in. # Print out the standard deviation on height. Replace 'None'
stddev = np.std(np_baseball[:,0])
# np_baseball is available
print("Standard Deviation: " + str(stddev))
# Import numpyimport numpy as np
# Print out correlation between first and second column. Replace 'None'
# Create np_height_in from np_baseball
corr = np.corrcoef(np_baseball[:,0], np_baseball[:,1])
np_height_in = np_baseball[:,0]
print("Correlation: " + str(corr))
# Print out the mean of np_height_in
print(np.mean(np_height_in)) Blend it all together
 Convert heights and positions, which are regular lists, to numpy # Print out the median height of other players. Replace 'None'
arrays. Call them np_heights and np_positions.
 Extract all the heights of the goalkeepers. You can use a little trick print("Median height of other players: " + str(np.median(other_heights)))
here: use np_positions == 'GK' as an index for np_heights. Assign the
result to gk_heights.
 Extract all the heights of all the other players. This time
use np_positions != 'GK' as an index for np_heights. Assign the result
to other_heights.
 Print out the median height of the goalkeepers using np.median().
Replace None with the correct code.
 Do the same for the other players. Print out their median height.
Replace None with the correct code.

# 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)))

You might also like