#This is a comment. Use comments to describe code
# You can uncomment chunks using Cmd (or Ctrl) + /
x = 5 #int
v = 2.0 #float
z = False #bool
y = "Hello World" #string
#You can also initialize multiple comma-separated variables at once:
a,b,c = 1,2,3 # Creates the three variables a,b,c, and assigns them values 1,2,3, respectively
print(x)
print(v,z,y) # You can print multiple comma-separated values at once
5
2.0 False Hello World
x = 5+3-2
print(x)
x = 7*6/2
#print(x)
# Order of operations is enforced, and parentheses are supported
x = (5+3)*2 / 4
#print(x)
# Exponentiation is supported with the (**) operator
x = 2**3
#print(x)
# Other built-in operators are the modulo operator (%), which calculated the 'remainder' of division between two values...
x = 17%4
#print(x)
#... as well as the floor division operator (//), which gives the result of divison between two values rounded down to the nearest integer.
x = 17//4
#print(x,y)
6
x = 5.0
#print(x)
x += 3 # Update the value of x by adding 3
#print(x)
x /= 2 # Update the value of x by dividing 2
#print(x)
# You can also use the variable itself in an update expression in Python.
x = 5.0
x = x + x*x
#print(x)
x = 5.0
# print(x == 5)
# print(x < 5)
# print(x <= 5)
# print(not(x <= 5))
# print(not(x == 10))
#A common pitfall is to confuse = (an assignment operator) with == (a Boolean operator). Don't do this!
# = is used to initialize variables
# == is used to compute whether or not two variables are equal.
y = 3.0
# print((y == 50.) or ( x== 5.0))
# print((y == 50.) and ( x== 5.0))
# print(not((y == 50.) and ( x== 5.0)))
# print(not((y == 3.0) or ( x== 5.0)))
# print(True == False)
x = [1, 2, 3, 4, 5] #This is a list
#print(len(x))
#print(x[0])
#print(x[-1])
#print(x[0:2])
#print(x[0:4:2])
#print(3 in x)
#print(7 in x)
# You can mutate lists in-place
x.append(6)
#print(x)
x.remove(4)
#print(x)
x[3] = 7
#print(x)
#You can also use lists that contain other lists. The number of nested lists can be thought of as a 'dimension'.
# Uncomment each line of code below, and provide a brief commented explanation of what each line does:
y = [[1, 2], [3, 4], [5, 6]] #This is a 2-D list
#print(len(y))
#print(y[0])
#print(y[0][0])
#print(y[1:3][0:2])
# You will find that we will use large, multidimensional lists/arrays (i.e. matrices and tensors) frequently in machine learning.
x = [1.0, 2.0, 3.0, 4.0, 5.0]
y = 6
print(x*y)
[1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0]
x = [1.0, 2.0, 3.0, 4.0, 5.0]
counter = 0 # Start with index 0
while counter < len(x): # As long as we're working with an index found in x
x[counter] *= 6 # Multiply the element at the counter index by 6
counter += 1 # Iterate the counter so that we move to the next index on our next pass through this code block.
print(x)
# Notice that the block of code has stopped executing now that the counter has reached a value of 5;
# at this point the conditional in the 'while' loop is no longer true and the indented block of code stops running.
print(counter)
[6.0, 12.0, 18.0, 24.0, 30.0]
5
x = [1.0, 2.0, 3.0, 4.0, 5.0]
new_x = [] # Initialize an empty list to hold our new values
for i in x: # For all of the elements 'i' in list x:
new_x.append(i * 6) # Multiply the element by 6 and add it to the new list.
print(new_x)
[6.0, 12.0, 18.0, 24.0, 30.0]
x = [1.0, 2.0, 3.0, 4.0, 5.0]
for i in range(len(x)): # For all indices in list x
x[i] *= 6 # Mutate the element at that index by multiplying it with 6
print(x)
[6.0, 12.0, 18.0, 24.0, 30.0]
x = [1.0, 2.0, 3.0, 4.0, 5.0]
x = [y*6 for y in x] #x is the list of each element 'y' of x multiplied by 6
print(x)
# The tradeoff here is between code readability and compactness
[6.0, 12.0, 18.0, 24.0, 30.0]
a = [10.0, 11.0, 12.0, 13.0, 14.0, 15.0]
b = [4.0, 3.0, 5.0, 6.0, 4.0, 3.0]
# While Loop:
# For loop:
#(Challenge) List comprehension:
x = 5
# if (x % 2 == 0):
# print("x is even")
# else:
# print("x is odd")
y = 3
# if (x > y):
# print("x is greater than y")
# elif (x < y):
# print("x is less than y")
# else:
# print("x is equal to y")
# Write your code here:
def sum(list_to_sum):
"""Finding the sum of all the elements in a list
Args:
list_to_sum: The list whose elements will be summed over
Returns:
list_sum: the total sum of the list
"""
list_sum = 0
for i in list_to_sum:
list_sum += i
return list_sum
#Verify that this function works
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
z = [2, 4, 6, 8]
w = [1, 3, 5, 7]
# print(sum(x))
# print(sum(y))
# print(sum(z))
# print(sum(w))
#Write your function here:
#Test the funtion here:
print(my_control_flow_fn(2))
print(my_control_flow_fn(3.0))
print(my_control_flow_fn("Hello!"))
print(my_control_flow_fn(True))
print(my_control_flow_fn([1,2,3,4]))
Execution Error
NameError: name 'my_control_flow_fn' is not defined
def greet(name="Shriram", time_of_day="morning"):
"""Prints a greeting
Args:
name: A string indicatnig the name to gree
time_of_day: A string indicating the time of day
"""
print("Hello, " + name + ". Good " + time_of_day + "!")
greet() # This will run the generic arguments
greet(time_of_day="evening") #If we want to change a generic argument, we state it ths way
greet(name="Andy")
greet(name="Professor Rotskoff", time_of_day="afternoon")
# You can mix and match generic arguments with arguments that always require user input as well.
Hello, Shriram. Good morning!
Hello, Shriram. Good evening!
Hello, Andy. Good morning!
Hello, Professor Rotskoff. Good afternoon!
#Write the function here:
#Test the function here
a = [10.0, 11.0, 12.0, 13.0, 14.0, 15.0]
b = [4.0, 3.0, 5.0, 6.0, 4.0, 3.0]
print(list_subtraction_fn(a,b))
class Animal():
#Notice the standard documentation for classes is similar to that of functions
"""Defines an Animal
Attributes:
species: A string indicating the species type
position: A list indicating the x and y positions of the animal
"""
#We initialize the value of all of the class attributes in the __init__ function (i.e. the "constructor")
#This function is run automatically whenever a new class object is created.
def __init__(self, species="monkey"):
self.species=species #Use 'self' to self-reference the object. In this case, we tell the object, once created, to set its own species attribute.
self.position = [0, 0]
#Class functions often change the attributes of the object somehow
#Here, we define two class functions that change the position attribute of our animal
def move_vertical(self, amount = 1): # The first argument to class functions is always 'self'
"""Moves function vertically by amount
Args:
amount: distance to move vertically by
"""
self.position[1] += amount
def move_horizontal(self, amount = 1):
"""Moves function horizontally by amount
Args:
amount: distance to move horizontally by
"""
self.position[0] += amount
#Let's create a dog and move it around!
a = Animal("dog")
print(a.species)
a = Animal() # This Animal object will have the generic species, since we didn't pass one as an argument
print(a.species)
print(a.position)
a.move_vertical()
print(a.position)
a.move_horizontal()
print(a.position)
dog
monkey
[0, 0]
[0, 1]
[1, 1]
class Dog(Animal):
"""Defines a Dog which subclasses Animal
Attributes:
name: A string indicating the name of the dog
"""
def __init__(self, name="Buster"):
super().__init__(species="dog") #We need to call the constructor of the 'super' (more general) class when we create a new subclass
self.name = name #We then take care of the assignment of the attributes specific to this subclass
def bark(self):
print("Bark!")
d = Dog()
print(d.species)
print(d.position)
d.move_vertical()
print(d.position)
d.move_horizontal()
print(d.position)
print(d.name)
d.bark()
dog
[0, 0]
[0, 1]
[1, 1]
Buster
Bark!
A Note on Python Libraries and Packages
import numpy
print(sqrt(4))
Execution Error
NameError: name 'sqrt' is not defined
print(np.sqrt(4))
2.0
2.0
x = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
y = x*6
print(y)
[ 6. 12. 18. 24. 30.]
# Write your function here:
#Test the function here
a = np.array([10.0, 11.0, 12.0, 13.0, 14.0, 15.0])
b = np.array([4.0, 3.0, 5.0, 6.0, 4.0, 3.0])
print(array_subtraction_fn(a,b))
[ 8. 9.5 9.5 10. 12. 13.5]