By Salerno | February 29, 2020
1. Defining functions
def square(number):
print("The square of", number, "is", number ** 2)
square(7)## The square of 7 is 492. Functions with multiple parameters
def maximum(value1, value2, value3):
max_value = value1
if value2 > max_value:
max_value = value2
if value3 > max_value:
max_value = value3
return max_value
maximum(12, 27, 36)## 36maximum('yellow', 'red', 'orange')## 'yellow'3. Random-Number Generation
import random
random.seed(10)
for roll in range(10):
print(random.randrange(1,7), end=" ")## 5 1 4 4 5 1 2 4 4 3
import random
for i in range(20):
print("H" if random.randrange(2) == 0 else "T", end=" ")## H H T T H H T H T H T T T T T T H T T H4. Unpacking tuples
student = ("Sue", [89, 94, 85])
name, grades = student
print(f'{name}: {grades}')## Sue: [89, 94, 85]5. Math Module Functions
import math
math.ceil(9.2)## 10math.floor(9.2)## 9math.exp(9.2)## 9897.129058743909math.log(9.2)## 2.2192034840549946math.log10(9.2)## 0.9637878273455552math.pow(3, 2)## 9.0math.sqrt(49)## 7.0math.fabs(-10)## 10.0math.fmod(9.8, 4.0)## 1.80000000000000076. Default Parameter Values
def rectangle_area(length=2, width=3):
return length * width
rectangle_area()## 6rectangle_area(10)## 30rectangle_area(10, 5)## 507. Arbitrary Argument Lists
def average(*args):
return sum(args) / len(args)
average(5, 10)## 7.5average(5, 10, 15)## 10.0average(5, 10, 15, 20)## 12.5grades = [88, 75, 96, 55, 83]
average(*grades)## 79.48. Methods: Functions that belong to objects
s = "Hello"
s.lower()## 'hello's.upper()## 'HELLO's
## 'Hello'9. Scope rules
#acessing a global variable from a function
x = 7
def access_global():
print('x printed from access_global:', x)
access_global()## x printed from access_global: 7
# trying to modify a global variable
def try_to_modify_global():
x = 3.5
print('x printed from try_to_modify_global:', x)
try_to_modify_global()## x printed from try_to_modify_global: 3.5x## 7
def modify_global():
global x
x = 'hello'
print('x printed from modify_global:', x)
modify_global()## x printed from modify_global: hellox## 'hello'10. Import
from math import ceil, floor
ceil(10.7)## 11floor(10.7)## 10# wildcards
from math import *
e## 2.71828182845904511. Binding names for modules and module identifiers
import statistics as stats
grades = [85, 93, 45, 87, 93]
stats.mean(grades)## 80.612. Object Identities
id(grades)## 42661728813. Data Science: Measures of Dispersion
import math, statistics
y = [-2.5, -0.5, -1.5, 2.5, 1.5, -0.5, 0.5, 1.5, -1.5]
statistics.pvariance(y)## 2.4691358024691357statistics.pstdev(y)## 1.5713484026367723math.sqrt(statistics.pvariance(y))## 1.571348402636772314. Example
from sklearn import datasets
import pandas as pd
iris = datasets.load_iris()
data_iris = iris.data
digits = datasets.load_digits()
data_digits = digits.data
type(iris)## <class 'sklearn.utils.Bunch'>type(data_iris)## <class 'numpy.ndarray'>type(digits)## <class 'sklearn.utils.Bunch'>type(data_digits)
## <class 'numpy.ndarray'>