Professional Documents
Culture Documents
Crash Course
Crash Course
DICTIONARIES
INPUT
FUNCTIONS
CLASSES
MATPLOTLIB CH 15
DICTIONARY
Comprises of key-value pairs:
empty_dictionary = {} # declaring empty dictionary, to which key-value pairs can be added later
dictionary1 = {‘color’ : ‘green’,} # dictionary declared.
print (dictionary1[‘color’]) # prints ‘green’ as it is the value of key ‘color’. A key’s value can
be a number, string, list or another dictionary.
dictionary_new = {
‘rehan’ = ‘ali’,
‘faizan’ = ‘ali’,
‘zain’ = ‘abid’,
} # longer dictionaries can be written like this.
NOTE: All calls to elements of list, tuple or keys of dictionaries use ‘[]’ brackets.
LOOPING in Dictionaries:
for a, b in dictionary1.items():
print (“Key: ” + a)
print (“Value: ” + b) # a, b or any other variables can be used.
if value variable not given in loop, then only keys are accessed by default, i.e.
for variab in dictionary1:
print (variab) # This will also have the same result as above.
set()
when set() is wrapped around a list containing duplicate items, python builds a set of unique items only.
set( dictionary1.values() ) # builds a set of unique values from dictionary1
NESTING
Dictionaries in lists:
list_of_dictionaries = [dictionary1, dictionary2]
Lists in Dictionaries:
dictionary = { ‘key1’ : ‘value1’, ‘key2’ : [ value_a, value_b, value_c, ‘string’ ] }
for loop can also be used in case of lists included in dictionaries.
Dictionary in Dictionaries:
WHILE LOOP
Runs as long as a certain condition is true.
using while loop along with user input to determine if to quit program:
if a while loop starts with while=True it will run forever until we use break statement (elaborated ahead)
USING FLAG:
For a program that should run as long as many conditions are true, we can define a variable which
determines whether or not the entire program is active. It’s a flag; acts as a signal to the program.
Programs run when the flag is set to true and stops when its false.
while program_active:
name = input (prompt)
if name == ‘quit’:
program_active = False
else:
print (name)
current_number = 0
while current_number <10:
current_number += 1
if current_number % 2 == 0:
continue
print (current_number)
SYNTAX NOTE: List, tuple, dictionary calling & list slicing use ‘[]’ – big brackets whereas all methods &
functions use ‘()’ – small brackets.
FUNCTIONS
Passing Arguments:
Positional arguments:
def describe_pet (name, type):
print (name)
print (type)
Keyword Arguments:
def describe_pet (name, type):
print (name)
print (type)
Default Parametervalues:
def describe_pet (name, type = ‘dog’):
print (name)
print (type)
NOTE: Parameter with default value must be listed at the end at the time of function declaration.
Return Values:
- return statement takes value from inside function and returns it back to the line that called the
function.
- functions can process data and return a value or set of values.
Returning Dictionary:
def build_person(first_name, last_name, age=''):
"""Return a dictionary of information about a person."""
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person
while True:
# Get user name through input function and print neatly formatted name using function.
f_name = input (“Please enter first name: ”)
l_name = input (“Please enter last name: ”)
formatted_name (users)
NOTE: when * is used before parameter; python makes tuple of all the arguments passed at the time of
calling function.
NOTE: Python matches positional & keyword arguments first, & then collects any remaining arguments
in the final parameter. First value is stored in the parameter size and remaining in a tuple.
Syntax:
class Dog():
def sit(self):
print (self.name + “ is sitting.”)
Syntax explained:
- by convention, class names start with capital letters.
- self parameter is required before all other parameters in the method definition in classes.
Accessing Attributes:
print (my_dog.name)
print (my_dog.age)
- dot notation is used to access object (‘my_dog’ –it is the instance which was created from Dog class
and stored in variable ‘my_dog’) attributes, and in this case we access the value of my_dog attributes
name and age. Attributes are accessible outside the class due to the self parameter.
Calling Methods:
my_dog.sit()
- dot notation is used to call any method from a class.
Multiple instances can be created.
class Car():
def __init__(self, make, model):
self.make = make
self.model = model
def get_name(self):
car_name = (“Car name: ” + self.make + “, Car model: ” + self.model)
return car_name
my_car.update_odometer(23)
my_car.increment_odometer(100)
INHERITANCE
When one class inherits from another, it takes all attributes and methods from the first class.
original class = parent class
new class = child class
- super() function is a special function that python needs to make a connection between the child &
parent class. it tells python to call __init__() method from ElectricCar’s parent class which gives an
ElectricCar instance all the attributes of its parent class.
Instances as Attributes:
Say we add many attributes & methods for battery like type, age, capacity, mileage etc. It can be
desirable to move them to a separate class Battery() and then use Battery instance as an attribute in
ElectricCar class.
class Battery():
def __init__(self, type = 70):
self.type = type
def battery_name(self):
print (“Car battery name: ” + self.type)
class ElectricCar(Car):
def __init__(self, make, model):
super(). __init__(make, model)
self.battery = Battery() # instance Battery() added as attribute here.
File Paths:
- if in same folder, only file name required.
- relative path is required, e.g. if program is in folder ‘example’ and file is in folder ‘files’ and ‘files’
folder is in the same folder i.e. ‘example’ then path will be ‘ with open(‘files\filename.txt’) – Windows
require back slash (\) for paths – please remember.
Writing to a file:
3 arguments: ‘w’ - write mode, python erases all data on file and then opens it.
‘r’ - read mode, if no argument is given then file is opened in read mode by
default.
‘a’ - append mode, adds/appends the data at the end of the file object.
‘r+’ - read and write to the file.
- write method is used to write to files no matter what argument is used.
- if a file does not exist and we use open() function then python creates the file no matter what
argument is used.
Exceptions:
- Handling ZeroDivionException:
use try-except block, as it is used to avoid traceback errors:
try:
print(5/0) # the code which might generate error goes here.
except ZeroDivisionError:
print (“You cannot divide a number by 0”) # the code that should be
executed in case of
error goes here.
Handling FileNotFoundError exception:
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
print (“Sorry, file not found.”)
Analyzing Text:
- Gutenberg.org - classic literature texts
- .split() method: separates a string into parts where it finds a space and stores all string parts in a
list.
Note: some punctuation will appear with some of the words.
title = “Alice in Wonderland”
title.split() [‘Alice’, ‘in’, ‘Wonderland’]
example: count all no. of words in Alice in Wonderland.
with open(filename) as f_obj:
contents = f_obj.read() # sets the f_obj to variable contents.
words = contents.split()
number_of_words = len(words)
print (number_of_words)
Note: a function with argument as file name + path can be defined to count the number of words in
each file. def count_words(filename). Further, file name can be a list of files. Moreover, for loop can be
used to analyze/return the number of words in all files.
MATPLOTLIB – CHAPTER 15
matplotlib.pyplot
Basic graph:
import matplotlib.pyplot as plt
plt.plot(variable, linewidth=2) # plots the graph with provided data on only y-axis.
plt.title(“title”, fontsize=2) # set chart title.
plt.xlabel(“labelx”, fontsize=4) # set label axes.
plt.ylabel(“labely”), fontsize=4) # set label axes.
plt.tick_params(axis=’both’, labelsize=14) # set the size of tick labels
plt.show() # show the graph
Correcting graph:
plt.plot(variable1, variable2, linewidth=14) # plots the graph with provided data on x and y
axis, first variable is plotted on x-axis.
Range of axis:
plt.axis ([0, 100, 0, 120]) # First two values for x-axis, second two values for y-axis. –ve
value can also be given for axis range.
Scatter() arguments:
edgecolor=‘none’ # removes the edge of scatter points, useful when plotting a lot of
points and edgecolor joins together to make a line.
c=’red’ # defines the color of scatter points.
c=(0, 0, 0.8) # color can be given in RGB (red, green, blue) from 0 to 1.0 value.
Using colormaps:
colormap is a series of colos in a gradient that moves from a starting to ending color.
Argument:
plt.scatter(x_val, y_val, c=y_val, cmap=plt.cm.Blues, edgecolor=’none’, s=40)
# list of y values passed to c, then we tell pyplot which colormap to use through the
cmap argument.
# All colormaps available on matplotlib.org/ - go to Examples, scroll down to color
examples, & click colormaps_reference.
File: random_walk.py
From random import choice
Class RandomWalk(): # a class to generate random walk
def __init__(self, num_points=5000): # Initialize attributes of a class
self.num_points = num_points
self.x_values = [0] # All walks start at (0,0)
self.y_values = [0]
def fill_walk(self): # A function to determine the limit of steps, their direction, & distance
while len(self.x_values) < self.num_points:
File: rw_visual.py
import matplotlib.pyplot as plt
from random_walk import RandomWalk
while True: # Using while loop so that randomwalks are repeatedly generated
rw = RandomWalk
rw.fill_walk()
plt.figure(figsize=(10,6)) OR plt.figure(dpi=128, figsize=(10,6))
# altering figure size, by default python assumes that screen resolution is 80 pixels per inch, you can
change it using the second(right hand side) example above.
point_numbers = list(range(rw.num_points))
# generating list equal to the number of points to use colormap
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
# axis has been cleared so the randomwalk is displayed without axis
plt.show()
Rolling Dice with Pygal (www.pygal.org/ click Documentation, then click chart types.)
File: die.py
from random import randit
class Die():
def roll(self):
return randit(1, self.num_sides)
Rolling dice, analyzing result of the rolls, & making histogram thereof:
File: roll.py
From die import Die