PythonNotes
PythonNotes
radius = 6
area = area_of_a_circle(radius)
print(area)
#113.04
Parameters are used when defining a function. Below, a and b are parameters.
ex) def add(a, b)
return a + be
Arguments are the names of the inputs supplied when a function is called.
ex) sum = add(5, 6)
print() is a function that prints a value to the console. It does not return
a valie
return is a keyword that ends the function's execution. IT gives the spcified
value back to the caller. It does NOT print anything to the console.
print() in functions is useful to help debug values, but it MUST be removed
after testing.
Logic
print(True and True)
# prints True
print(True or False)
# prints True
If-else statements
if statements can be followed by 0 or more elif (standing for else-if)
statements, which can be followed by 0 or more else statements
ex) if score > high_score:
print('High score beat!')
elif score > second_highest_score:
print('you got second place!')
elif score > third_highest_score:
print('you got third place!')
else:
print('Better luck next time')
if the above used all if statements, they could all execute multiple
times
The body of the For Loop MUST include an indent (conventionally four
spaces)
the range(start, limit, step) The function will not meet or exceed the
limit parameter. The step determeines how much the function incremets or decrements
(+1 is the default)
ex) for i in range(0, 10, 2):
print(i)
#Prints 0,2,4,6,8
ex) for i in range(3, 0, -1)
print(i)
#prints 3,2,1
Lists are called "Arrays" in other languages. Declared using square brackets,
seperated by commas:
ex) inventory = ["Iron Breastplate", "Healing Potion", "Leather Scraps"]
Lists can contain any data type.
.pop() is the inverse of .append(): it takes off the last item on the list
and returns it for use:
ex) vegetables = ["broccoli", "cabbage", "kale", "tomato"]
last_vegetable = vegetables.pop()
#vegtables = ["broccoli", "cabbage", "kale"]
#last_vegetable = "tomato"
using items[i] will scan each item in the list, and increment the count for
each item, with [i] being the index of item, icremented by the for loop
If you don't need to no the index numbers of a list, you don't need to pull
them:
trees = ["oak", "pine", "maple"]
for tree in trees:
print(tree)
# This returns oak / pine / maple, without their indices.
Lists can be divided with the slicing operator (:)
Syntax: my_list[ star : stop : step]
A negative index counts from the end of the list, so that numbers[-1:]
gives the last item, numbers[-2:] gives the penultimate item et c.
ex) numbers[-3:] #gives [7, 8, 9]
del nums[1:3]
# yields [1, 4, 5, 6, 7, 8, 9]
del nums[:]
# removes all items but leaves the empty list.
To find differences between two lists, use a for-in loop, with an if x
not-in loop:
ex) for item in grocery_list:
if item not in items_purchased:
unpurchased_items.append(item)
Tuples are most often used for groups of 2 or 3 items, such as names
and ages.
When storing single items as tuples, you must include a comma so
Python knows it marks a tuple and not regular parentheses
ex) dog = ("Fido",)
Multiple tuples can be stored within a list. When pulling an item from
a tuple within a list, the first index [0] is the tuple itself, [1] is the first
item et c.
ex) my_tuples = [("this is the first tuple in the list", 45,
True),("this is the second tuple in the list", 21, False)]
print(my_tuples[0][0]) # this is the first tuple in the
list
print(my_tuples[0][1]) # 45
print(my_tuples[1][0]) # this is the second tuple in the
list
print(my_tuples[1][2]) # False
names_dict = {}
for name in names:
# .split() returns a list of strings
# .split() returns a list of strings
#where each string is a single word from the original
name_lst = name.split()
print(names_dict)
# Prints: {'jack': 'bronson', 'jill': 'mcarty', 'john': 'denver'}
Keys can be removed using the del keyword. If a key does not exist, you will
receive an error:
names_dict = {
"jack": "bronson",
"jill": "mcarty",
"joe": "denver"
}
del names_dict["unknown"]
#ERROR
counts[file_type] = counts.get(file_type, 0) + 1
The above line checks if file_type is in the dictionary, if not it usese 0 as
the default count. It then adds 1 to the default or current count.
then it assigns the new value to the dictionary
Before python 3.7, dictionaries were unordered, and you could not iterate
them.
Sets are like Lists, but are unordered and unique- only one value may occur in a
set.
ex) fruits = {"apple", "banana", "grape"}
print(type(fruits)
#prints <class "set">
print(fruits)
#prints {"banana", "grape", "apple"}
to create an empty set, you must use the set() function- using curly brackets
creates a dictionary.
ex) fruits = set()
iterating over values in a set does not guarantee order.
to create a class, use the class keyword and set custom properties as
follows:
ex) class Soldier:
health = 5
Classes can be used to create custom methods, unlike dictionaries which may
seem similar.
A method being a function that is associated with a classm and has access to
all properties of the object.
ex) class soldier:
health = 5
soldier_one = Soldier()
soldier_one.take_damage(2)
print(soldier_one.health)
#prints '3'
Methods will always take a special paramater as their first argument called
self. This references to the object itself, allowing you to read and update the
properties of the object.
ex) object.method()
south_wall = Wall()
south_wall.height = 20 #only updates this instance of a
wall
print(south_wall.height)
#prints "20"
north_wall = Wall()
print(north_wall.height)
#prints "10"
Class variables remain the same between instances of the same class are
declared at the top levels. It is generally best not to use class variables.
class Wall:
height = 10
south_wall = Wall()
print(south_wall.height)
# prints "10"
print(south_wall.height)
# prints "20"
Encapsulation:
Makes code easier for humans to understand by hiding superfluous information.
A function is an example of encapsulation- the caller doesn't need to interact with
what's inside it, just what it takes in and puts out.
Code can also be encapsulated using private and public members. A user can
interact with a public member, but not private members.
While definitions are always changing, I like to think about abstraction and
encapsulation in the following way.
OOP groups data and behavior together, treating programming as a modeling problem:
"How can I create a class that simulates data and behavior of a real human?"
Functional programing treats code as inputs and outputs: "When a human acts, what
are the inputs and what are the outputs that affect my program state?"
Inheritance allows one class to inherit the properties and methods of another class
(the parent class).
One class can inherit from another using the following syntax:
class Animal:
#parent "Animal" class
class Cow(Animal):
# child class "Cow" inherits "Animal"
To use the constructor of another class, use the built-in super() method:
class Animal:
def __init__(self, num_legs):
self.num_legs = num_legs
class Cow(Animal):
def __init_(self)
#call the parent constructor to give cow legs
super().__init__(4)
When a child class inherits from its parent, it inherits everything
That said, we should always be careful that each time we inherit from a base
class the child is a strict subset of the parent.
You should never think to yourself "my child's class needs a couple of the
parent's methods, but not these other ones" and still decide to inherit from that
parent.
Polymorphism describes the trait of OOP that allows classes in the same
hierarchical tree to have methods with the same name, but different behaviors.
ex) class Creature():
def move(self):
print("the creature moves")
class Dragon(Creature):
def move(self):
print("the dragon flies")
class Kraken(Creature):
def move(self):
print("the kraken swims")
for creature in [Creature(), Dragon(), Kraken()]
creature.move()
# prints:
# the creature moves
# the dragon flies
# the kraken swims
class Archer:
def hit_by_fire(self):
self.health -= 10
return self.health
Both methods have the same name, take 0 inputs, and return integers. If
any of those things were different, they would have different function signatures.
Custom classes don't have support for operators such as + by default. They
can be added manually however, such as below:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def get_book_text(path):
with open(path) as f:
return f.read()
def get_word_count(text):
words = text.split()
return len(words)
main()
In Python, you check if a string is empty using the boolean context of the string
in the if condition. However, here, you are using if doc == False: which is not the
Pythonic way to check if a string is empty.
the function above converts the lists formats1 and formats2 into sets, and
returns the common entries in both.
In Python, the built-in map function takes a function and an iterable (in this case
a list), and returns a new iterable where the function has been applied to each
element of the original iterable.
This allows us to compose functions that operate on entire lists without having to
write a loop and store state in variables
def square(x):
return x * x
nums = [1, 2, 3, 4, 5]
squared_nums = map(square, nums)
print(list(squared_nums))
# [1, 4, 9, 16, 25]
Self:
In Method Definitions:
you must include self as the first parameter in instance of methods of
a class definition. This allows Python to know which instance of the class to use.
class Bear:
def __init__(self, name):
self.name = name
def speak(self):
return f"I am {self.name}, a wizard bear!"
def introduce(self):
greeting = self.speak()
return greeting
def speak(self):
return f"I am {self.name}, a wizard bear!"
import re