Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

INDEX:

DICTIONARIES

 INPUT

 FUNCTIONS

 CLASSES

 FILES & EXCEPTIONS

 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.

Adding key value pairs:


dictionary1[‘new_key’] = ‘new_value’ # adds key ‘new_key’ with value ‘new_value’ at end of
dictionary
dictionary1[‘key_2’] = ‘50’ # adds key ‘key_2’ with value ‘50’ at end of dictionary

Modifying key value pairs:


dictionary1[‘color’] = ‘yellow’ # changes ‘color’ key value from ‘green’ to ‘yellow’.

Removing key value pairs:


del dictionary1[‘new_key’] # Permanently deletes the key ‘new_key’ and its value.

LOOPING in Dictionaries:

Looping through all key value pairs:

for key, value in dictionary1.items():


print (“Key: ” + key)
print (“Value: ” + value) # prints all keys and values in dictionary1 using for loop.

for a, b in dictionary1.items():
print (“Key: ” + a)
print (“Value: ” + b) # a, b or any other variables can be used.

Looping through only keys:

for variab in dictionary1.keys():


print (variab) # prints all the keys in dictionary1

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.

Looping through only values:


for variab in dictionary1.values():
print (variab) # prints all the values in dictionary1

.keys() .items() .values()


.keys() & .items() & .values() methods do not just access keys or all items of dictionary, they actually
return a list of all the keys or items of a dictionary.

print (dictionary1.keys()) OR print (dictionary1) # gives list of keys only


print (dictionary1.values()) # gives list of values only
print (dictionary1.items()) # gives list of key value pairs like ( [ (key,value), (key,value) ] )

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]

Example of for loop in nested dictionary:


alien1 = { ‘color’ : ‘green’, ‘speed’ : ‘medium’, ‘points’ : 10 }
alien2 = { ‘color’ : ‘white’, ‘speed’ : ‘super_fast’, ‘points’ : 100 }
aliens = [alien1, alien2]

for alien in aliens:


if alien[‘color’] == ‘green’:
alien [‘color’] = ‘blue’
alien [‘speed’] = ‘fast’
alien [‘points’] = 40

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:

scientists_dictionary = { ‘rehan’ : { ‘first_name’ : ‘rehan’, ‘last_name’ : ‘ali’, ‘age’ : 32}, ‘faizan’ :


{ ‘first_name’ : ‘faizan’, ‘last_name’ : ‘ali’, ‘age’ : 29} }

for key, value in scientists_dictionary.items():


full_name = value ['first_name'] + value ['last_name']
age = value ['age']
print ("Full name: " + full_name)
print ("Age: " + str(age))
# prints the information of scientist rehan & faizan which is stored as a dictionary within a dictionary.
INPUT
input() function pauses program and waits for user input. once input is received, python stores it in
variable.
name_variable = input (“Please enter your name: ”) # prompts “Please enter your name: “ and
stores the input received in
name_variable.

Inputting integers / floats instead of strings:


By default input() stores inputted data as strings only. Numbers can be stored as follows:
variable_number_input = int ( input (“Please enter a number: “) )
print (variable_number_input + 10) # inputted number will be added to 10 and result will be
printed
Modulo operator %
This operator returns the remainder only: 10 % 2 returns 0, 10 % 3 returns 1
can be used to find out if a number is even or odd like: if number % 2 == 0

WHILE LOOP
Runs as long as a certain condition is true.
using while loop along with user input to determine if to quit program:

prompt = “Please enter name, or enter ‘quit’ to end the program”


name = “”

while name != ‘quit’:


name = input (prompt)
if name != ‘quit’:
print (name)

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.

prompt = “Please enter name, or enter ‘quit’ to end the program”


name = “”
program_active = True

while program_active:
name = input (prompt)
if name == ‘quit’:
program_active = False
else:
print (name)

Using break to exit loops:


Program ends immediately without executing any more code.

prompt = “Please enter name, or enter ‘quit’ to end the program”


name = “”
while True:
name = input (prompt)
if name == ‘quit’:
break
else:
print (name)

Using continue to go to the beginning of the loop:


continue allows to go to start of a loop without breaking it completely, a conditional test can be applied.
consider a program that displays only the odd numbers from to 10.

current_number = 0
while current_number <10:
current_number += 1
if current_number % 2 == 0:
continue
print (current_number)

Using While loops in lists:


unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# Verify each user until there are no more unconfirmed users.
# Move each verified user into the list of confirmed users.
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)

# Display all confirmed users.


print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())

Using remove() method in loops:

while ‘cat’ in animals_list:


animals_list.remove(‘cat’)

SYNTAX NOTE: List, tuple, dictionary calling & list slicing use ‘[]’ – big brackets whereas all methods &
functions use ‘()’ – small brackets.
FUNCTIONS

Defining function: def a_function:


print (“Assalam o Alaikum ! ”)
Calling function: a_function()
A function can be called as much times as needed
Passing info to function: def b_function(any_name):
print (“Assalam o Alaikum ! ” + any_name.title() )
b_function (‘rehan’)
# above function calling uses ‘rehan’
parameter – (like any_name in above example) is a piece of information the function needs to do its job.
any_name mentioned above is a variable.
argument – (like rehan above) is a piece of information which is passed from a function call to function.
when the argument ‘rehan’ was passed to the function ‘b_function()’, its value was stored in the
parameter any_name.

Passing Arguments:

Positional arguments:
def describe_pet (name, type):
print (name)
print (type)

describe_pet (‘jag’, ‘dog’)


arguments must be in the same order as the parameter.

Keyword Arguments:
def describe_pet (name, type):
print (name)
print (type)

describe_pet (name = ‘jag’, type = ‘dog’)


order can be ignored when calling function as keyword arguments are used.

Default Parametervalues:
def describe_pet (name, type = ‘dog’):
print (name)
print (type)

describe_pet (name = ‘jag’) # Both have same result


describe_pet (‘jag’) # Both have same result

NOTE: Parameter with default value must be listed at the end at the time of function declaration.

Equivalent function calls (position, keyword, & default arguments together):


# A dog named Willie.
describe_pet('willie')
describe_pet(pet_name='willie')
# A hamster named Harry.
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster', pet_name='harry')
# Above all have the same output.
- Parameters whose default value is not given; its argument must be given 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 simple value with an optional argument:


def get_formatted_name(first_name, last_name, middle_name=''):
"""Return a full name, neatly formatted."""
if middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name
else:
full_name = first_name + ' ' + last_name
return full_name.title()

musician = get_formatted_name('jimi', 'hendrix')


print(musician)

musician = get_formatted_name('john', 'hooker', 'lee')


print(musician)

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

musician = build_person('jimi', 'hendrix', age=27)


print(musician)

Using function with while loops:


def formatted_name (first_name, last_name):
full_name = first_name + “ ” + last_name
return full_name.title()

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: ”)

print (formatted_name (f_name, l_name))


# Above last line of code can also be written as:
get_formatted_name = formatted_name (f_name, l_name)
print ( get_formatted_name )

Passing a list to a function:


A list can also be passed to function at the time of function call, mentioning dictionary name in the
argument. A for loop can be embedded in function body then to make a greeting / perform an action on
all elements of a list.

users = [‘rehan’, ‘faizan’, ‘ali’]

def formatted_name (list_name):


for user_name in list_name:
print (“Hello ” + user_name + “ !”)

formatted_name (users)

Modifying a list in function:


List modification already discussed, this concept only embeds it in function.

Preventing functions to modify lists:


Use list copy method at the time of function calling to avoid list modification.
function_name ( list_name [:] )

Passing arbitrary number of arguments:


when asterisk ( * ) is preceding the parameter in function definition line, it allows to collect as many
arguments as the passing line provides.

NOTE: when * is used before parameter; python makes tuple of all the arguments passed at the time of
calling function.

def make_pizza ( *toppings ):


print (toppings)
make_pizza (‘pepperoni’, ‘mushroom’, ‘jalapeno’)

Mixing positional and arbitrary arguments:


def make_pizza ( size, *toppings ):
print (toppings)
make_pizza (‘medium’, ‘pepperoni’, ‘mushroom’, ‘jalapeno’)

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.

Arbitrary keyword arguments:


a dictionary can be built using arbitrary keyword arguments especially when we do not know what type
of information will be received from users, syntax is **, this syntax creates empty dictionary and fills
with user provided key value pairs.

def user_profile (name, age, **user_info):


profile = {}
profile [‘name’] = name
profile [‘age’] = age
for key, value in user_info.items():
profile [key] = value
return profile
rehan_profile = user_profile (‘rehan’, 32, hobby = ‘programming’, job = ‘banker’)
print (rehan_profile)
Storing functions in Modules:
we can store functions in a separate file (module) and import modules in programs.
- A module is a file ending in .py
- importing makes python copy all code from module to your program behind the scenes first.

Calling function from imported module:


- module name . function name.
- Example: to call a function from module name: pizza, function name: make_pizza syntax will be
pizza.make_pizza()
- module_name.function_name()

Importing specific functions:


- from module_name import function_name
- from module_name import function_1, function_2, function_3
- example: from pizza import make_pizza # note that braces () are not mentioned.
- after importing functions can be called without module name, just like as if function was written in the
same program.

Use as to give a function an alias:


- can be used when imported function name might conflict with an existing function name in program.
- from pizza import make_pizza as mp

Use as to give a module an alias:


- allows calling module functions more easily.
- import pizza as p
- functions in pizza modules can be written as p.make_pizza(16, ‘pepperoni’)

Importing all functions from a module:


from pizza import *
- copies all functions from pizza module to current program and functions can be used without module
name.
CLASSES

- classes used to represent real world things & objects.


- instantiation: is making an object from a class. and you work with instances of a class (called objects).
- a function that’s part of a class is called a method.

Syntax:
class Dog():

def __init__(self, name, age):


self.name = name
self.age = age

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.

The __init__() method:


- it is python’s default method.
- two underscores _ before init and two after it prevent python’s default method names from conflicting
with user defined method names.
- whenever __init__ method is called later on i.e. whenever creating an instance (object) of class, the
method will automatically pass the self argument.
- Every method call associated with a class automatically passes self, it is a reference to the instance
itself.
- self gives the individual instance access to the attributes and methods inside the class.
- when we make an instance from dog class, we will pass Dog () a name and age, self is passed
automatically, no need to pass self.
- variables declared in __init__ are prefixed with self. variables prefixed with self are available to other
methods of the class and can also be accessed through instances created from the class.

Making an instance from class:


my_dog = Dog(‘tommy’, 3)
# Here python calls the __init__ method(function) in class Dog with arguments ‘ tommy’ and 3.
# __init__ method creates an instance and sets the name and age attributes using the provided
values at the time of calling function.
# __init__ method does not have any return statement but python automatically returns an
instance representing this particular dog. & we store that instance in variable my_dog.

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.

Working with Classes & Instances


- Discusses how to modify attributes associated with a particular instance.

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

Setting a default value for an attribute:


In case you want to give default value for an attribute, you can do so in __init__ method and you don’t
have to include a parameter for that attribute in __init__ method:
class Car():
def __init__(self, make, model):
self.make = make
self.model = model
self.odometer_reading = 0

Modifying attribute values


3 ways to do it.

Modifying attribute value directly:


simplest way is to access value directly through an instance.
my_car = Car(‘audi’, 2013)
my_car.odometer_reading = 23

Modifying an attribute’s value through a method:


we can add a method (function) inside a class to update attribute’s value. say we add:
def update_odometer(self, mileage):
self.odometer_reading = mileage

my_car.update_odometer(23)

Incrementing an attribute’s value through a method:


sometimes incrementing is required instead of rewriting attribute’s value.
def increment_odometer(self, miles):
self.odometer_reading += miles

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

__init__() method for child class:


say we create ElectricCar class from Car class, we only write attributes specific to electric car only.
When an instance is created from the child class, first thing is that python assigns values to all attributes
in the parent class.the __init__() method of child class needs help:
class ElectricCar (Car):
def __init__(self, make, model)
super().__init__(make, model)
my_car = ElectricCar(‘subaro’, 2018)

- 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.

Defining attributes and methods for the child class:


class ElectricCar (Car):
def __init__(self, make, model)
super().__init__(make, model)
self.battery_size = 70

Overwriting methods from the parent class:


define a method in the child class with the same name as the parent class, python will disregard the
parent class method.

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.

my_car = ElectricCar(‘subaro’, 2018)


my_car.battery.battery_name() #
FILES & EXCEPTIONS
Reading an entire file:
with open(‘filename.txt’) as file_object:
contents = file_object.read()
print (contents)
- Keyword ‘with’ closes file once access to it is no longer needed, python determines when to
close the file. It’s best option to use ‘with’ instead of using close () function.
- open(‘’) function returns an object representing the file, it needs one argument i.e. filename
(along with its path - if its not in the same folder/directory). open(‘’) returns and object representing
the file and we store this object in variable file_object.
- .read() method reads the entire contents of the file and store it as one long string in contents
variable. Note: this method also reads new line and tabs present in text files which can be removed
using .rstrip, .lstrip, .strip methods. Further, read() method gives an empty string at the end of each file
it reads because there is no data at end of file and it is shown by a blank line.

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.

Reading line by line:


- It is often needed to read line by line to find certain text / replace certain text.
with open(filename) as f_object:
for line in f_object:
print (line)
- Note: new line character causes blank line printing at the end of each line of text file, we use
strip to adjust whitespace.

Making a list of lines from a file:


- file opened in with (); access only available within the with() function block, if we need access to
it outside the block, we will need to store file’s lines inside a list and then work with that list outside the
block.
with open(filename) as f_object:
lines = f_object.readlines()
for line in lines:
print (line.rstrip())
- .readlines() method takes each line from the file and store it in a list, the list is then stored in the
variable ‘lines’. ‘lines’ now represents a list of all the lines of ‘filename’.

Working with file’s contents:


- we can do whatever we want with the strings of the file once stored in a list; say we can
combine all strings on one line. e.g.
with open(filename) as f_object:
lines = f_object.readlines()
pi_string = ‘’
for line in lines:
pi_string += line.rstrip()
print (pi_string)
print (len(pi_string))
- If the file we are working with is large, say it has 1,000,000 digits then we can compute all and
print only selective digits on screen:
print (pi_string[:53] + “…”)
print (len(pi_string))

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.

with open(file, ‘w’) as f_obj:


f_obj.write(“I love python”))

with open(file, ‘a’) as f_obj:


f_obj.write(“I love python”))

Writing multiple lines:


‘\n’ newline character is needed to write multiple lines, otherwise python writes appends data on the
same line.

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.

Plotting and styling individual points using scatter():


plt.scatter(x, y, s=100) # s stands for size

Plotting a series with scatter():


x_val = [1, 3, 5, 7, 9]
y_val = [2, 4, 6, 8, 10]

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.

Saving plots automatically:


replace plt.show() with plt.savefig():
plt.savefig(‘plot1.png’, bbox_inches=’tight’)
# second argument trims extra whitespace from the plot. If this space is needed, omit this
argument.
# only png format saving is available.
Random Walks:
No clear direction, water molecules in a drop of water, pollen on surface of water drop remains on top
due to this random walk motion of molecules and hence the pollen motion is also random.

Need to create RandomWalk() Class which needs only three attributes:


1) Variable to store the number of points in the walk
2) List to store the x-coordinates
3) List to store the y-coordinates

Need to import choice() function from the random library.

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:

x_direction = choice([-1,1]) # x direction can be –ve/+ve


x_distance = choice([0,1,2,3,4,5]) # x distance can be 0 to 5
x_step = x_direction * x_distance # x step

y_direction = choice([-1,1]) # y direction can be –ve/+ve


y_distance = choice([0,1,2,3,4,5]) # y distance can be 0 to 5
y_step = y_direction * y_distance # y step

if x_step==0 and y_step==0: # reject steps that go nowhere


continue # go to start of function if step=0

next_x = self.x_values[-1] + x_step # calculates next x value in list


next_y = self.y_values[-1] + y_step # calculates next y value in list

self.x_values.append(next_x) # Appends the next x value to the list


self.y_values.append(next_y) # Appends the next y value to the list

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.scatter(rw.x_values, rw.y_values, s=10, c=point_numbers, cmap=plt.cm.Blues,


edgecolor=’none’)
# plotting scatter plot for the random walk using colormap

plt.scatter(0,0,c=’green’, edgecolors=’none’, s=100)


# plotting starting point

plt.scatter(rw.x_values[-1], rw.y_values[-1], c=’red’, edgecolors=’none’, s=100)


# plotting ending point

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()

keep_running = input(“Make another walk (y/n): “)


if keep_running == ‘n’:
break
# using if loop; if user wants to generate another random walk or end the program.

Rolling Dice with Pygal (www.pygal.org/ click Documentation, then click chart types.)

Need to create Die class


Need to import randit function from the random library

File: die.py
from random import randit

class Die():

def __init__(self, num_sides=6)


self.num_sides = num_sides

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

You might also like