###Python basic operations ##Check Python version import sys print(‘Python: {}’.

###Python basic operations
##Check Python version
import sys
print(‘Python: {}’.

###Python basic operations
##Check Python version
import sys
print(‘Python: {}’.format(sys.version))
###############################################################################
##1 Arithmetic
# Python as a calculator
# Addition and subtraction
4+4
print(4+4 +5)
# Space does not matter
print(5 – 5)
# Multiplication and division
print(3 * 5)
print(10 / 2)
# Exponentiation
print(4 ** 2)
# Modulo
print(18 % 7)
#More complicated math functions do not exist in Python base package
sin(30) #NameError: name ‘sin’ is not defined
import math
math.sin(30)
dir(math) # all available functions in “math”
###############################################################################
##2 Python variables, types and operators
#Python has five standard data types:
#-Numbers
#-String
#-List
#-Tuple
#-Dictionary
#In Python, a variable allows you to refer to a value with a name.
#Python is case sensitive
#To create a variable use “=”, like this example:
print (“John is 20 years old” )
print (“He doesn’t like being 20 years old” )
age = ’20’
print (“John is “+ age +” years old,” )
print (“He doesn’t like being ” + age+ ” years old” )
weight = 60
height = 1.7
bmi = weight/height**2
bmi
#You can now use the name of this variable, weight, instead of the actual value,
60.
#Remember, = in Python means assignment, it doesn’t test equality!
#To check the type of a variable:
type(bmi) # bmi is a float
x=3 # x is an integer
y=’I love Python’ # y is a string
z=True # z is a boolean
type(x)
type(y)
type(z)
#Different types have different operation rules, for example,
2+3
True + False
True – False
False-True
#and, or, not operators
True and False
True or False
not (True and False)
3>4
3==4
3==3.0
3!=3
‘ab’+’cd’
‘ab ‘+’cd’
a+a #name ‘a’ is not defined
#local and global variable
x=10
def myfun(x):
y=x**2
x=4
return y
myfun(x)
myfun(5)
myfun(2)
x
###############################################################################
##3. Data structures: list, array, dictionary and dataframe
##3.1. Lists are a simple container of items, much like arrays in many languages.
#They can change size at any time, can contain items of different types.
list_family_member = [‘Mom’, ‘Dad’, ‘Son’, ‘Daughter’]; list_family_member
list_family_height1 = [‘Mom’, 1.65, ‘Dad’, 1.85, ‘Son’, 1.79, ‘Daughter’, 1.52]
print(list_family_height1)
#Check the type of a list
type(list_family_height1)
##index pointer: zero based indexing and backward indexing
list_family_height1[0]
list_family_height1[7]
list_family_height1[-1]
list_family_height1[-8]
#list slicing
list_family_height1[2:4] #the ending index “4” is not included
list_family_height1[:4]
list_family_height1[4:]
##You saw that a Python list can contain practically anything; it can even contain
other lists!
x = [[“a”, “b”, “c”],
[“d”, “e”, “f”],
[“g”, “h”, “i”]]
x
#To subset a list of lists, you can use the same technique as before: square
brackets.
x[2]
x[2][0]
#x[2] results in a list, that you can subset again by adding additional square
brackets.
x[2][:2]
#Replace/delete/extend list elements
x = [“a”, “b”, “c”, “d”]
x[1] = “r”; x
x[2:] = [“s”, “t”]
x
del(x[1]);x #del() is associated with an index
x.remove(‘s’); x #remove() is associated with an element
y = x + [“e”, “f”]; y
y.append(“z”);y
y.clear();y #clear() to empty a list
#Exercise #1
#The areas of the different parts of your house are stored in separate variables,
#as shown below:
# area variables (in square meters)
hall = 11.25
kit = 18.0
liv = 20.0
bed = 10.75
bath = 9.50
#a. Create a list of lists “areas” such that each sub-list contains the name of
each room as a string
#More specifically, use the strings “hallway”, “kitchen”, “livingroom”, “bedroom”
and “bathroom” for
#the appropriate locations and then its corresponding area.
#b. Sum of the areas of kitchen and bedroom and name it “eat_sleep_area”
#c. Use two different ways of slicing to create a new list, “downstairs”, that
contains the first 3 sub-lists of areas.
#d. Do a similar thing to create a new variable, upstairs, that contains the last 2
sub-lists of areas.
#e. You did a miscalculation when determining the area of the bathroom;
#it’s 10.50 square meters instead of 9.50. Can you make the changes?
#Make the areas list more trendy! Change “livingroom” to “chillzone”.
#f. Use the + operator to paste the list [“poolhouse”, 24.5] to the end
#of the areas list. Store the resulting list as areas_1.
#g. Further extend areas_1 by adding data on your garage. Add the string
#”garage” and float 15.45. Name the resulting list areas_2
#h. remove the “poolhouse” and its corresponding float from the areas list.
#List summary
#Powerful
#Collection of values
#Hold different types
#Change, add, remove
#Question: Can we perform mathematical operations over lists?
height = [1.73, 1.68, 1.71, 1.89, 1.79]
height
#Out: [1.73, 1.68, 1.71, 1.89, 1.79]
weight = [65.4, 59.2, 63.6, 88.4, 68.7]
weight
#Out: [65.4, 59.2, 63.6, 88.4, 68.7]
weight / height ** 2
#TypeError: unsupported operand type(s) for **: ‘list’ and ‘float’
###############################################################################
##3.2 We’ll need other data structures such as array (can be created using array()
#from “numpy” module)
#if we want to perform mathematical operation over the data,
#array operation offers element-wise calculations
###############################################################################
###Pyhton package installation
#list all the modules installed in your system
help(“modules”)
#check if a module ‘numpy’ is installed
help(‘numpy’) # documentation will be found if previously installed
help(‘pulp’) #no documentation can be found if not installed
import sys
‘numpy’ in sys.modules
#To install a package, use “!pip install” or “!conda install”
pip install pulp
help(‘pulp’) #shows the documentation for the module
#If the installation doesn’t work for you, try the following excerpts
#import pip
#pip.main([“install”, “pulp”])
#If not try
#sudo pip install pulp
? numpy # object is not found if not imported even it is installed
import numpy
array([1, 2, 3])
# NameError: name ‘array’ is not defined
numpy.array([1, 2, 3])
#Alternatively,
import numpy as np
np.array([1, 2, 3])
#We can also import a function from a module
from numpy import array
array([1, 2, 3])
#or
from numpy import * #very inadvisable practice-function member may be mixed up
array([1, 2, 3])
#output: array([1, 2, 3])
##Exercise #2
#Import the ‘math’ package so you can access the constant pi with math.pi.
#Calculate the circumference of the circle and store it in C, C=2pir
#Calculate the area of the circle and store it in A,A=pir^2
#Print out the results as
#Circumference: C
#Area: A
# Selectively only import pi from the math package
#you can always make your import more selective.
###############################################################################
np_height = np.array(height)
np_height
#Out: array([ 1.73, 1.68, 1.71, 1.89, 1.79])
np_weight = np.array(weight)
np_weight
type(np_weight)
#Out: array([ 65.4, 59.2, 63.6, 88.4, 68.7])
bmi = np_weight / np_height ** 2
bmi
#array([ 21.852, 20.975, 21.75 , 24.747, 21.441])
65.4/1.73**2
#NumPy remarks: it contains only one type!
np.array([1.0, “is”, True])
#array([‘1.0’, ‘is’, ‘True’],
# dtype=’ 23
#Out: array([False, False, False, True, False], dtype=bool)
bmi[bmi > 23]
#Out: array([ 24.747])
##Exercise #3
# a. Create list baseball_height that contains data of the baseball players’ height
in inches
baseball_height = [74, 69, 71, 73, 76, 79, 75, 81]
#Use np.array() to create a numpy array from baseball_height. Name this array
np_baseball_height.
#Print out the type of np_baseball_height to check that you got it right.
#convert the units to meters by Multiplying np_baseball_height with 0.0254.
#Store the new values in a new array, np_baseball_height_m.
#Print out np_baseball_height_m and check if the output makes sense.
# b. Create list baseball_weight that contains data of the baseball players’ weight
in pounds
baseball_weight = [174, 210, 181, 193, 230, 200, 185, 190]
#Create a numpy array from the baseball_weight list. Name this array
np_baseball_weight.
#Multiply by 0.453592 to go from pounds to kilograms. Store the resulting numpy
array as np_baseball_weight_kg.
#Use np_baseball_height_m and np_baseball_weight_kg to calculate the BMI of each
player.
#Print out bmi
#c. Create a boolean numpy array: the element of the array should be True if the
corresponding
#baseball player’s BMI is below 21. You 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 the bmi array. ##2D NumPy Arrays #Type of NumPy Arrays type(np_height) #Out: numpy.ndarray type(np_weight) #Out: numpy.ndarray #ndarray = N-dimensional array np_2d = np.array([[1.73, 1.68, 1.71, 1.89, 1.79], [65.4, 59.2, 63.6, 88.4, 68.7]]) np_2d #Out:array([[ 1.73, 1.68, 1.71, 1.89, 1.79], # [ 65.4 , 59.2 , 63.6 , 88.4 , 68.7 ]]) np_2d.shape #(2, 5); 2 rows, 5 columns np.array([[1.73, 1.68, 1.71, 1.89, 1.79], [65.4, 59.2, 63.6, 88.4, "68.7"]]) #array([['1.73', '1.68', '1.71', '1.89', '1.79'], # ['65.4', '59.2', '63.6', '88.4', '68.7']], # dtype='v>1.5}
dict_doubleCond
# Dictionary has other Replace/delete/extend operations that are similar to list
Dict_family_height1[‘Mom’] = 1.60;Dict_family_height1
# Delete a single element
del Dict_family_height1[‘Mom’];Dict_family_height1
# Delete all elements in the dictionary
Dict_family_height1.clear();Dict_family_height1
#Exercise #5
#In a supply chain system, there were 7 customers, namely “customer1”,
“customer2″…”customer7″
#and their corresponding demands are 20,35,60,70,42,80,15
StrDemand =”customer”
DemandKeys=[]
for i in range(1,8):
DemandKeys.append(StrDemand+str(i))
DemandKeys
DemandValues=[20,35,60,70,42,80,15]
#a. Creates a dictionary “demand” to store the demand information and use the name
of the customers
#as the keys. First create two lists for keys and values respectively and then make
dictionary from them.
#b. What is the demand of customer7?
#c. The demand of each customer is increased by 20% in the next season. Create the
new dictionary “newdemand”.
#d. Find out the customers who have demand between 21 and 50.
###############################################################################
#3.4 Data frame is a 2-D labeled data structure with columns of potentially
different type (like an excel sheet).
#DataFrame makes data manipulation easy, from selecting or replacing columns and
indices to reshaping data
## Create a dataframe – a function from Pandas module
#Create a dataFrame with 3 months of sales information for 3 companies
account Jan Feb Mar
0 Jones LLC 150 200 140
1 Alpha Co 200 210 215
2 Blue Inc 50 90 95
#3.4.1 The “default” manner to create a DataFrame from python is to use a list of
dictionaries.
#In this case each dictionary key is used for the column headings. A default index
will be
#created automatically:
help(“pandas”)
? pandas
import pandas
import pandas as pd
sales = [{‘account’: ‘Jones LLC’, ‘Jan’: 150, ‘Feb’: 200, ‘Mar’: 140},
{‘account’: ‘Alpha Co’, ‘Jan’: 200, ‘Feb’: 210, ‘Mar’: 215},
{‘account’: ‘Blue Inc’, ‘Jan’: 50, ‘Feb’: 90, ‘Mar’: 95 }]
sales
type(sales)
df = pd.DataFrame(sales)
df
type()
#3.4.2 Alternatively, use from_dict()
sales = {‘account’: [‘Jones LLC’, ‘Alpha Co’, ‘Blue Inc’],
‘Jan’: [150, 200, 50],
‘Feb’: [200, 210, 90],
‘Mar’: [140, 215, 95]}
df = pd.DataFrame.from_dict(sales)
df
sales
#3.4.3 Use lists to create dataframe
#This is a row oriented approach using pandas from_records().
#This approach is similar to the dictionary approach but you need to explicitly
#call out the column labels.
sales = [(‘Jones LLC’, 150, 200, 50),
(‘Alpha Co’, 200, 210, 90),
(‘Blue Inc’, 140, 215, 95)]
labels = [‘account’, ‘Jan’, ‘Feb’, ‘Mar’]
df = pd.DataFrame.from_records(sales, columns=labels)
df
### Exercise 6
#Create the following datafame in two ways (using dictionary and list)
one two three four
a 1.0 1 10.0 11.0
b 2.0 2 20.0 22.0
c 3.0 3 30.0 33.0
#a. From dictionary
#b. From list
##############################################################################
##4. Functions
#Next we learn how to define (create) functions and how to use them.
# In order to define a function, we need to use a reserved word “def”
#A function also has a body, which is indented
#In order for a function to run, it must be called into action.
#Otherwise, a function will not run by itself
#Function hello1 below requires no argument.
#To run it, you need just to call it by typing its name in the program body
#This function returns nothing back
def hello1():
print (“hello world inside the function”)
return
hello1() ##To run it, you need just to call it
#Function hello2 requires one argument.
#Upon calling this function, you have to pass it an argument
def hello2(x):
print (x)
return
hello2()#TypeError: hello2() missing 1 required positional argument: ‘x’
hello2(‘I love Python’)
x=56
hello2(x)
#Function hello3 below requires no argument.
#To run it, you need just to call it by typing its name in the program body
#This function returns content of x
def hello3():
x = “hello world passed to script”
return(x)
hello3()
#Function hello4 below requires no argument.
#To run it, you need just to call it by typing its name in the program body
#This function returns nothing
#Notice that there is no call of this function in the program body
def hello4():
x= “hello world will not be printed as I am not called in the program body”
#this is just an assignment and will not return anything if x is not called
return
hello4()
#Define funtions to do calculation
def sumProblem(x, y):
sum = x + y
print(sum)
sumProblem(2, 3)
def main():
a = int(input(“Enter an integer: “))
b = int(input(“Enter another integer: “))
print( sumProblem(a, b))
main()
#Excercises 7
#Create the following 2 functions.
#a. Write a function “function1”:It takes three argument, all strings. The function
returns the concatenated three arguments.
#test the function with the three strings: I, love, Python. The expected results is
“l love Python”
#b. Write a function “function2”: It takes 3 arguments, three numbers. The function
returns the Max of three arguments.
#test the function with numnbers 2, 3 and 4. Hint: you can first define a funtion
that returns the max of two arguments
#and then define the funtion that returns the max of the three aguments. Use “if”
syntax for condtion
###############################################################################
##5. Loop
#The excerpts bellow helps you to master loop functions
#We create two sets of numbers, and symbols (which is also strings)
list_num = [1, 2, 3, 4, 5]
list_str = [“@”, “#”, “$”, “%”, “&”]
for number in list_num:
print (‘Number_FOR: ‘, number)
#newlist=[]
#for i in list_num:
# i=1+i
# newlist.append(i)
#newlist
#Use for loop to extract data from dictionary
Dict_family_height1= {‘Mom’: 1.65, ‘Dad’: 1.85, ‘Son’: 1.79, ‘Daughter’: 1.52}
Dict_family_height1[‘Mom’]
for i in Dict_family_height1: #i refers to the keys
print(i)
for i in Dict_family_height1: #i refers to the keys
print(Dict_family_height1[i])
num=0
while (num < 5): print ('Number_while: ', list_num[num]) num = num +1 # we get the length of the list_str from the set itself #range(a, b): a, a+1, a+2, ..., b-1 range(len(list_str)) for index in range(len(list_str)): print ('Current String_FOR: ', list_str[index]) #or for data in list_str: print ('Current String_FOR: ', data) #Since we know the number of elements in the set, the above loop could be also written like this: SP=0 while (SP < 5): print ('Current String_while: ', list_str[SP]) SP = SP +1 # we can also build lists using loop, first start with an empty one elements = [] # then use the range function to do 0 to 5 counts for i in range(0, 6): print ("Adding %d to the list." % i) #%d is a space holder for numbers # append is a function that lists understand elements.append(i) elements #Now, we create one nested loop, i.e., a loop inside another loop for vertical in range(1, 6): print (vertical) for horizontal in ['a','b','c']: print (horizontal) # Exercise 8 #a. Write a function "function3": use loop function to sum all the numbers in a list. #The contents of the list should be user specified #Hint: use "+=" operator #Sample List : [4, 2, 7, 1, 3] #Expected Output : 17 #b. Write a function "function4": use loop function to print the even numbers from a given list. #Hint: even number means n % 2 == 0 #Sample List : [4, 10, 13, 14, 50, 61, 70, 87, 90] #Expected Result : [4, 10, 14, 50, 70, 90] # The "+=" and *=" operators bmi bmi+=bmi #"+=" if number, add the right hand side to the left hand side bmi*=2 #"*=" if number, multiply the right hand side to the left hand side #"+=" and *=" are useful in looping