Udacity Data Scientist Nanodegree : Prerequisite — Python(L2, L3, L4)

Lesson 2: Data Types and Operators / Lesson 3: Control Flow / Lesson 4: Functions

Lesson 2: Data Types and Operators

Cautions!

4.445e8 = 4.445 * 10 ** 8

Arithmetic Operators

Variables

Integers and Floats

>>> print(.1 + .1 + .1 == .3)
False

String

this_string = 'Simon\'s skateboard is in the garage.'
>>> Simon's skateboard is in the garage.

Split()

new_str = "The cow jumped over the moon."
new_str.split()
>>> ['The', 'cow', 'jumped', 'over', 'the', 'moon.']
new_str.split(' ', 3)
>>> ['The', 'cow', 'jumped', 'over the moon.']
new_str.split('.')
>>> ['The cow jumped over the moon', '']

Slice and Dice with Lists

>>> list_of_random_things = [1, 3.4, 'a string', True]
>>> list_of_random_things[1:2]
[3.4]
>>> list_of_random_things[:2]
[1, 3.4]
>>> list_of_random_things[1:]
[3.4, 'a string', True]

Mutability and Order

>>> my_list = [1, 2, 3, 4, 5]
>>> my_list[0] = 'one'
>>> print(my_list)
['one', 2, 3, 4, 5]
>>> greeting = "Hello there"
>>> greeting[0] = 'M'

Useful Functions for Lists

name = "-".join(["García", "O'Kelly"])
print(name)
>>> García-O'Kelly

Tuple

dimensions = 52, 40, 100
length, width, height = dimensions
print("The dimensions are {} x {} x {}".format(length, width, height))

Sets

numbers = [1, 2, 6, 3, 1, 1, 6]
unique_nums = set(numbers)
print(unique_nums)
>>> {1, 2, 3, 6}

Dictionaries

elements = {"hydrogen": 1, "helium": 2, "carbon": 6}
print("carbon" in elements)
print(elements.get("dilithium"))
True
None
n = elements.get("dilithium")
print(n is None)
print(n is not None)
True
False

Lesson 3: Control flow

Indentation

If — Good and Bad Examples

For Loops

Iterating Through Dictionaries with For Loops

cast = {
"Jerry Seinfeld": "Jerry Seinfeld",
"Julia Louis-Dreyfus": "Elaine Benes",
"Jason Alexander": "George Costanza",
"Michael Richards": "Cosmo Kramer"
}
for key, value in cast.items():
print("Actor: {} Role: {}".format(key, value))
Actor: Jerry Seinfeld    Role: Jerry Seinfeld
Actor: Julia Louis-Dreyfus Role: Elaine Benes
Actor: Jason Alexander Role: George Costanza
Actor: Michael Richards Role: Cosmo Kramer

While Loops

Break, Continue

Zip and Enumerate

Zip

letters = ['a', 'b', 'c']
nums = [1, 2, 3]
for letter, num in zip(letters, nums):
print("{}: {}".format(letter, num))
some_list = [('a', 1), ('b', 2), ('c', 3)]
letters, nums = zip(*some_list)

Enumerate

letters = ['a', 'b', 'c', 'd', 'e']
for i, letter in enumerate(letters):
print(i, letter)
0 a
1 b
2 c
3 d
4 e
x_coord = [23, 53, 2, -12, 95, 103, 14, -5]
y_coord = [677, 233, 405, 433, 905, 376, 432, 445]
z_coord = [4, 16, -6, -42, 3, -6, 23, -1]
labels = ["F", "J", "A", "Q", "Y", "B", "W", "X"]

points = []
for point in zip(labels, x_coord, y_coord, z_coord):
points.append("{}: {}, {}, {}".format(*point))

for point in points:
print(point)
F: 23, 677, 4
J: 53, 233, 16
A: 2, 405, -6
Q: -12, 433, -42
Y: 95, 905, 3
B: 103, 376, -6
W: 14, 432, 23
X: -5, 445, -1
data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))data_transpose = tuple(zip(*data))
print(data_transpose)
((0, 3, 6, 9), (1, 4, 7, 10), (2, 5, 8, 11))

List Comprehensions

capitalized_cities = []
for city in cities:
capitalized_cities.append(city.title())
capitalized_cities = [city.title() for city in cities]

Conditionals in List Comprehensions

squares = [x**2 for x in range(9) if x % 2 == 0]
names = ["Rick Sanchez", "Morty Smith", "Summer Smith", "Jerry Smith", "Beth Smith"]first_names = [name.split()[0].lower() for name in names]
print(first_names)
>>> ['rick', 'morty', 'summer', 'jerry', 'beth']

Lesson 4: Functions

Function — Default Arguments

def cylinder_volume(height, radius=5):
pi = 3.14159
return height * pi * radius ** 2
cylinder_volume(10, 7)  # pass in arguments by position
cylinder_volume(height=10, radius=7) # pass in arguments by name

Variable Scope

# This will result in an error
def some_function():
word = "hello"
print(word)
# This works fine
def some_function():
word = "hello"
def another_function():
word = "goodbye"
# This works fine
word = "hello"
def some_function():
print(word)
some_function()

Documentation

def population_density(population, land_area):
"""Calculate the population density of an area. """
return population / land_area

Lambda Expressions

def multiply(x, y):
return x * y
multiply = lambda x, y: x * y
multiply(4, 7)

Iterators And Generators

def my_range(x):
i = 0
while i < x:
yield i
i += 1
for x in my_range(5):
print(x)
0
1
2
3
4

Why Generators?

理科與藝術交織成靈魂的會計人,喜愛戲劇與攝影,但也喜歡資料科學。