Programming Course
Programming Course
Python beginner
15th august, 2023
You type the variable name and type input as the value and two parenthesis
Comments are extra information that the programmer types to explain code
to the user
They are denoted by a hashtag
Iteration
Iteration is in a form of a loop and so helps repeat certain instructions
without typing them over and over again
How to perform iteration
For i in range(type the number of times to repeat the command):
Print(“hello”)
NB: indent the value that is going to be repeated
Introduce colon after the range
In iteration there is another loop called while loop
This instruction can be used to create an infinite loop or iteration under a specific
condition one uses logical operations when using while loop and the condition
must always be true
E.g.
Seats=30
While seats>0:
NB always use 0 when the counter(variable) is more than 1
Print(“sell tickets”)
Seats=seats-1
NB the loop command must still followed by a colon and must be indented
Output: it will output sell tickets 30 times and the last command means that it will
print sell tickets and it will keep reducing like a countdown till it reaches the 30 th
value. Then the iteration stops because the condition is no more true.
If one omits the last command (seats=seats-1)
Then it becomes an infinite loop
Remember I said that 0 is used in the while loop instruction here is an exception
Seats=0
While seats<4:
NB: because the counter(variable) is less than 1 the value 4 is used and indicates
the number of iterations
Print(seats)
Seats=seats+1
Output: since this time we are printing the counter and not another value the output
will start from 0 and add up till it reaches the 4th value (this is because the print
command is printing an integer not a string)
0
1
2
3
Thursday, August 31, 2023
There are other operations except the greater than and less than that can also
be used for logical operations that can also output Boolean
Print(5!=5)
Is five different from five output: true
Print(5>=9)
Is five greater than or equal to nine output: false
Print(5==5)
Is five equal to five output: true
Print(5<=9)
Selection
This is another way that a computer processes a command it allows the
computer to choose between two or more instructions if certain conditions
are met
E.g.
Seats=8
If seats>=3:
NB: next command must be indented
o Print(“enough space available”)
Else:
o Print(“sorry not enough space available”)
Because the number of spaces are more than or equal to three it is fulfilling
that condition therefore the computer will output enough space available
There is also another command called elif in the selection process
Elif means “else if”, it is used to add another condition before the else
command
If and else can also nest other if and else commands respectively
Monday, September 4, 2023
Lists
One can store more than one value in a variable
This is called creating a lists. This is how lists look like
Shopping_cart=[“milk”,”cereal”,”lettuce”]
NB: lists can store other data types like strings, floats, integers and Boolean
and even a mixture of them
The various values in a list a represented by an index
This is a number that is used to identify each item in a list
Indexing starts from zero at the left
If one wants to call out a value in a list stored in a variable
You must type the print command and in the parenthesis you must type the
variable name and type square brackets and then type the index that
represents the value you want to display
0 1 2
Movies=[“titanic”, “inception”, “quiet place”]
Print(Movies[1])
Output: inception
Slicing
o In lists, one can call out a particular portion of the list
o This is done by using a colon
o Animals=[ “cat”, ”dog”, ”ant” ]
0 1 2 3
Print(animals[0:2])
Output: cat, dog
Thursday, September 7, 2023
In slicing omitting the first index means that the slicing starts from the first word to
the index
Vehicles=[ “planes”, “lorries”, “trucks”, “buses” ]
0 1 2 3 4
Print(vehicles[:2])
Output: planes, lorries
Omitting the last index means the slicing begins from the first value excluding
itself
Vehicles=[ “planes”, ”lorries”, ”trucks”, ”buses” ]
0 1 2 3 4
Print(vehicles[1:])
Output: lorries trucks buses
Slicing with Negative indexing
Negative numbers can also be used for indexing
Animals=[ “goats”, ”cows”, ”dogs”, ”cats” ]
-4 -3 -2 -1 0
Print(animals[-3 : -1])
Output: cows dogs
Function
These are used to perform specific functions
A function is made up of two parts
Print(“a”)
1 2
1= function
2= argument
Examples of functions
Print
Range
Type
Input
NB: a function can contain another function
Print(type())
1 2 3
1=function
2=print’s argument
3= type’s argument
You can print more than 1 argument. You separate them with a comma
Print(“students:”,3)
Output: students:3
String functions
There are certain functions that are only used for strings
These are ; lower() upper() capitalize() and find()
lower(): it is used to change the cases of a string to lower case
print(“HIKING”.lower())
output: hiking
upper(): change lower case to upper case
print(“pipe”.upper())
output: PIPE
capitalize(): used to capitalize the first letter of a word
print(“ama”.capitalize())
output:Ama
find(): it is used to show the index of a character in a string. If there are more than
1 of the same character in the string, it will show the lowest index. If the character
is not present in the index the output will be -1
print(“cheaper”.find(“e”))
output: 2
print(“help”.find(“q”))
output: -1
NB: the dots after the strings are very important. Without the dot notation, the
function will result in an error
List functions
Len(): this is used to determine the number of items in a list
Names=[“james”, “paul”, “jane”]
Print(len(Names))
Output: 3
This function can also be used on strings
My_username=”lexy”
Print(len(My_username))
Output:4
The functions I will later talk about are specific to lists so use dot notation
Append(): it is used if u want to add an item at the end of a list
Friends=[“Adriana”, “Johnson”, “Rafiatu”]
Friends.append(“yasmine”)
Print(friends)
Output: Adriana,Johnson,rafiatu,yasmine
Insert(): it is used to replace the position a particular item in a list but doesn’t erase
that particular item. That item shifts its position
Cars=[“Bugatti”, “Lamborghini”, “Ferrari”]
Cars.insert(1,”benz”)
Print(cars)
Output: Bugatti,benz,Lamborghini,Ferrari
NB: the index is important
Pop(): it is used to remove an item from a list
Beautiful_towns=[“paris”, “rome”, “kasoa”, “dubai”]
Beautiful_towns.pop(2)
Output: paris, rome, dubai
Custom functions
In python, you can create your own functions.
Def greet():
Print(“hello, my friend.)
Greet()
Output: hello, my friend.
Def means you are defining a function. The print must be indented and a colon
must follow your function.
Some custom functions have no parameters, some have parameters. The greet
function above does not have a parameter but you can let it have an argument.
When calling a function the input in the parenthesis is no more called a parameter
but an argument
Def greet(name):
Print(“hello,name”)
Greet(alexandra)
Output: hello, alexandra
The function can also have more than one parameter. When calling a function type
the arguments in the correct order
Def my_identity(name,age):
Print(“about myself:” name,age)
My_identity(alexandra,45)
Output: about myself: alexandra,45
Index can be used to further illustrate what the arguments do. If the function will
be called more than once or stores two arguments use the return command
Def average(total,count):
Index= total/count
Return index
JHS3_classes=average(400,4)
JHS2_classes=average(645,5)
Output:100
129
Return cost,area
Cost,area=House_suitability(50000,300)
Print(cost,area)
Output=true,false
You can use the return value for only one argument to use only that one in the
function operation
Def house_suitability(cost,area):
Cost=cost<350,000
Area=area>400
Return area
House1=house suitability(50000,300)
Print(house1)
Output:false. This is because the area argument is being used
Python intermediate
Saturday, September 23, 2023
Dictionaries
These are like lists but store keys which are associated with other values
Cars={
1:”Toyota”,
2:”ferari”,
3:”Bugatti”,
}
NB: there must be closed in curly brackets and the items must be separated with
commas.
If you want to call out an item from a dictionary, you type the dictionary’s name
and the key (the first values before the colon) in square brackets and it will output
the value stored in the key
Print(cars[2])
Output:ferari
Print(cars[input()])
Takes key input an outputs its value if it is in the dictionary
The data stored in a dictionary must be immutable. Therefore you cannot store a
list in a dictionary because they are mutable.
“IN” and “NOT IN”
These words are used to determine if a specified value is in a dictionary
Designerclothes={
1: “Gucci”,
2:”Louis Vuitton”,
3: “Versace”,
“Dior”: true
}
Print(Balenciaga in designerclothes)
Output: false
Print(true not in designerclothes)
Output: false
Print(Gucci in designerclothes)
Output: true
Tuples
Tuples are like lists and the individual are also identified by indexes but they are
closed in parenthesis not square brackets
Dog_breeds=(“golden retriever”, “great dane”, “german shepherd”)
0 1 2
NB: the items in a tuple are immutable unlike lists where they are mutable. Trying
to change an item will result in an error
Disney_princesses=(“elsa”,”tiana”,”ariel”,”fairy godmother”)
Disney_princesses[3]=”aurora”
Print(Disney_princesses)
Output: error
Animals=(“cows”,[“dogs”,”sheep”])
0 1
Print(animals[1])
Output: dogs,sheep
You can decide not to enclose tuples in parenthesis
Animals=”cows”, “mouse”,”tick”
There is a function called dict() that can change any collection type to a dictionary
and list() to change other collection types to lists and set() can change any other
collection type to a list
E.g.
A phone stores contacts of people and their ages in tuples within a list. Write a
code so that someone inputs the name of the person and the person’s names and
age is displayed
Example
Input:james
Output:james is 46
Contacts=[
(“mark”,21),
(“james”,58),
(“Emily”,67)
]
Contacts=dict(contacts)
#converts the list into a dictionary in which the names are keys and the ages are
values
Name=input()
If name in contacts:
Print(name,”is”,contacts[name])
Else:
Print(‘not found’)
Tuple unpacking
Items in a tuple can be assigned different variables
Player_numbers=(7,10,24)
Ronaldo,messi,mbappe=Player_numbers
Print(Ronaldo)
Output: 7
Print(messi)
Output: 10
Print(mbappe)
Output: 24
Range can also be used in tuple unpacking
Solomon,tracy,Samantha,yasmine=range(4)
Print(Solomon)
Output: 0
Print(Tracy)
Output:1
Print(Samantha)
Output: 2
Print(yasmine)
Output:3
If there is asterisk before a variable it gets assigned the rest of the remaining values
a,b,c,*d,e=(1,2,3,4,5,6,7)
print(a)
output: 1
print(b)
output: 2
print(c)
output:3
print(d)
output:6
print(e)
output: 7
print(*d)
output:4,5
Sets
Sets are another collection type and it is enclosed in curly brackets except it
doesn’t have a key and a value like a dictionary and the items in a set are not
assigned indexes
Numbers={9,3,10,21,76}
Items in a set are not repeated
Print(Nums={6,5,2,8,9,3,2,7,8,7,6,5})
Output= 6,5,2,8,9,3,7
Set functions
Add() adds another element to a set and remove() removes an element from a list.
It uses dot notation
Even_numbers={2,4,6,8,10,11,12}
Even_numbers.add(14)
Even_numbers.remove(11)
Print(Even_numbers)
Output: 2,4,6,8,10,12,14
Sets also use “in” and “not in” like dictionaries. There are certain symbols used for
sets
Set1={1,3,5,7,9}
Set2={2,3,5,7,11,13}
|: this is used to join elements in two different sets like union in mathematics
without repeating elements
Print(Set1 | Set2)
Output: 1,2,3,5,7,9,11,13
& : this is used to determine the common element in both sets like
intersection in mathematics
Print( Set1&Set2)
Output: 3,5,7
- : this is used to determine the element in the first stated set that isn’t in
the second stated set
Print(Set1-Set2)
Output:1,9
Print(Set2-Set1)
Output:2,11,13
^ : it is used to make a set containing elements that are not in both sets
Print(Set1^Set2)
Output:1,2,9,11,13
Sunday, October 1, 2023
List comprehensions
They are used to create an iteration in a list and perform certain
operations on them
If you want to print the multiples of only even numbers or add any
special criteria you add if and your condition in the list comprehension
Nums=[ i*2 for i in range(10) if i*2 % 2==0]
Outputs the products of the even numbers from 0 to 10 and two
Print(Nums)
Output: 0,4,8,12,16,20
Multiples_of_three=[ i for i in range(20) if i % 3==0]
Print(Multiples_of_three)
Output: 0,3,9,12,15,18
It is not only numbers that are used in list comprehensions. In the case
of using strings the range function cannot be used
E.g.
Write a code using list comprehension to only output the consonants in
the word
Word= “Penelope”
Consonants=[ i for i in word if i not in (‘a’,’i’,’o’,’e’,’u’)]
Print(consonants)
Output: p,n,l,p
Thursday, October 5, 2023
List functions
Max(): used to determine the largest number in a list or in a portion of a
list
Min(): used to determine the least number in a list or a portion of a list
Abs(): used to determine the absolute value of a number or a number in
a list. The absolute value of a negative number is a positive number
Functional programming
Introductions
You can store a function in another function
Def numbers(func,arg):
Return Func(func(arg)
Def add_five(c):
Return C + 5
Result = numbers(add_five,8)
Print(result)
Output:18
Lambdas
This is another form of functional programming. It is like the def
function but instead it is written on one line unlike the def function
My_lambda = (lambda x:x**2)(4)
Print(my_lambda)
Output: 16
Lambdas can also store more than one argument
Another_example = (lambda x,r:x/2r)(3,6)
Print(another_example)
Output:0.25
Lambdas can be stored in functions
example
def my_func(f, arg):
return f(arg)
output: 16,27,38,49,60
NB: it is necessary to bring the list function before the map
To make It shorter u can use lambda’s instead of def
Example
nums = [11, 22, 33, 44, 55]
result = list(map(lambda x: x+5, nums))
print(result)
output: 16,27,38,49,60
scenario
salaries of employees and bonus is entered as input use map to
calculate the new salaries
whatever bonus you enter as input will be added with each item in the
list initial_salaries
filter
this is used to remove certain items in a list based on certain conditions
example
nums = [11, 22, 33, 44, 55]
res = list(filter(lambda x: x%2==0, nums))
print(res)
output: 22,44
to avoid typing the next function over and over again you use the for
loop to generate the iteration
When you want to use a generator and the while loop to subtract
numbers
Def subtracting_numbers():
i = 10
while i > 0:
yield i
i -=1
for i in subtracting_numbers():
print(i)
output: 10,9,8,7,6,5,4,3,2,1,0
using the for loop in generators can be used when you want to set a
range for the iteration
using a for loop in a generator to iterate even numbers between 10 and
20
def even_numbers(c,d):
for i in range(c,d):
if i %2 == 0:
yield i
for i in even_numbers(10,20):
print(i)
output: 12,14,16,18
print(list(numbers(11)))
output:[0,2,4,6,8,10]
Def text():
Print(‘hello’)
Decorated = decor(text)
Decorated()
Output: -----
Hello
-----
If you want the function to always output the decorated version you
must code it this way
Def decor(func):
Def wrap():
Print(‘-----‘)
Func()
Print(‘-----‘)
Return wrap
Def text():
Print(‘hello’)
text = decor(text)
text()
Output: -----
Hello
-----
@decor
Def text():
Print(‘hello’)
text();
Output: -----
Hello
-----
Def decor(func):
Def wrap(name):
Print(‘-----‘)
Func(name)
Print(‘-----‘)
Return wrap
@decor
Def text(name):
Print(‘hello’,name)
text(‘helen’);
Output: -----
Hello,helen
-----
Factorial example
def factorial(x):
if x <= 1:
return x
else:
return x * factorial(x-1)
print(factorial(5))
output: 120
print(fibonacci(4))
output: 3
this recursive function actually uses the indexes of the Fibonacci
sequence as an argument and returns the number the index represents
0, 1, 1, 2, 3, 5, 8, 13, 21…
0 1 23 4 5 6 7 8
Therefore entering 4 as an argument is actually an index representing 3
We can even use recursive functions to check if a number is odd or
even
def even(a):
if a%2 == 0:
return True
else:
odd(a - 1)
def odd(a):
return not even(a)
print(even(20))
output: true
print(odd(21))
output: true
print(even(21))
output:false
Else:
Return max(args)
Print(numbers(num:98,args:65,23,21,56,95,43))
Output:98
The args command allows us to input multiple arguments without
defining each argument in the function
NB: args returns the arguments as tuples
num = 34
def function(x,*args):
if x in range(18,26):
return list(filter(lambda x: x in range(18,26),args))
if x in range(26,36):
return list(filter(lambda x: x in range(26,36),args))
if x in range(36,46):
return list(filter(lambda x: x in range(36,46),args))
if x in range(46,56):
return list(filter(lambda x: x in range(46,56),args))
commonly = function(num,23,18,19,34,31,43)
print(commonly)
output:31,34
**kwargs
It is used to return arguments as dictionaries in a function. It also
doesn’t matter the number of arguments
def func(**kwargs):
return kwargs
def my_function(**kwargs):
for key,value in kwargs.items():
print(key,value)
common = my_function(name = 'alice',age = 25)
output:
name alice
age 25
in this output there is no colon curly brackets or commas so this is not a
dictionary but the kwargs command was used
Classes
Classes are used in object oriented programming(oop). It is used to
define objects(variables) and behaviours( methods)
These methods are functions stored within the class
class Cat:
def __init__(self, color, legs):
self.color = color
self.legs = legs
felix = Cat("ginger", 4)
rover = Cat("dog-colored", 4)
stumpy = Cat("brown", 3)
All methods must have self as their first parameter, although it isn't
explicitly passed, Python adds the self argument to the list for you; you
do not need to include it when you call the methods. Within a method
definition, self refers to the instance calling the method.
In this example, Cat instances have attributes color and legs. These can
be accessed by putting a dot, and the attribute name after an instance.
Example:
CODE PLAYGROUND: PY
class Cat:
def __init__(self, color, legs):
self.color = color
self.legs = legs
felix = Cat("ginger", 4)
print(felix.color)
output: ginger
In the example above, the __init__ method takes two arguments and
assigns them to the object's attributes. The __init__ method is called the
class constructor.
Remember, that all methods must have self as their first parameter.
These methods are accessed using the same dot syntax as attributes.
Example:
CODE PLAYGROUND: PY
class Dog:
def __init__(self, name, color):
self.name = name
self.color = color
def bark(self):
print("Woof!")
fido = Dog("Fido", "brown")
print(fido.name)
fido.bark()
output: fido
Woof
class Cat(Animal):
def purr(self):
print("Purr...")
class Dog(Animal):
def bark(self):
print("Woof!")
fido = Dog("Fido", "brown")
print(fido.color)
output: brown
fido.bark()
output: woof
if a subclass inherits the same attributes or methods as the superclass.
The subclass’s attributes and methods overrides the
superclass’s
class Wolf:
def __init__(self, name, color):
self.name = name
self.color = color
def bark(self):
print("Grr...")
class Dog(Wolf):
def bark(self):
print("Woof")
but if u want to call the method in the superclass even though u used the
same method in the subclass you can use the function super to call the
super class
class A:
def spam(self):
print(1)
class B(A):
def spam(self):
print(2)
super().spam()
B().spam()
Output:2,1
Here is an example using super class and subclass to calculate the area
and perimeter of a rectangle
class Shape:
def __init__(self, w, h):
self.width = w
self.height = h
def area(self):
print(self.width*self.height)
class Rectangle(Shape):
def perimeter(self):
print(2*(self.width+self.height))
w = int(input())
input: 12
h = int(input())
input: 42
r = Rectangle(w, h)
r.area() output:504
r.perimeter() output:1081
Wednesday, November 1, 2023
Magic methods
Magic methods are special methods which have double underscores at
the beginning and end of their names.
They are also known as dunders.
So far, the only one we have encountered is __init__, but there are
several others.
This means defining operators for custom classes that allow operators
such as + and * to be used on them.
CODE PLAYGROUND: PY
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
first = Vector2D(5, 7)
second = Vector2D(3, 9)
result = first + second
print(result.x)
print(result.y)
output: 8,16
The __add__ method allows for the definition of a custom behavior for
the + operator in our class.
As you can see, it adds the corresponding attributes of the objects and
returns a new object, containing the result.
Once it's defined, we can add two objects of the class together.
__sub__ for -
__mul__ for *
__truediv__ for /
__floordiv__ for //
__mod__ for %
__pow__ for **
__xor__ for ^
__or__ for |
There are equivalent r methods for all magic methods just mentioned.
class SpecialString:
def __init__(self, cont):
self.cont = cont
__eq__ for ==
__ne__ for !=
class SpecialString:
self.cont = cont
print(result)
spam = SpecialString("spam")
eggs = SpecialString("eggs")
spam > eggs
output:
>spam>eggs
e>spam>ggs
eg>spam>gs
egg>spam>s
eggs>spam>
As you can see, you can define any custom behavior for the overloaded
operators.
There are several magic methods for making classes act like containers.
__contains__ for in
There are many other magic methods that we won't cover here, such as
__call__ for calling objects as functions, and __int__, __str__, and the
like, for converting objects to built-in types.
import random
class VagueList:
def __init__(self, cont):
self.cont = cont
def __len__(self):
print(len(vague_list))
print(len(vague_list))
print(vague_list[2])
print(vague_list[2])
output:
B
B
We have overridden the len() function for the class VagueList to return a
random number.
The indexing function also returns a random item in a range from the
list, based on the expression.
This code is an example of using a class to determine the sum of the
width and heights of shapes and also return True if the area of the first
shape is bigger or false if proven otherwise
class Shape:
def __init__(self, w, h):
self.width = w
self.height = h
def area(self):
return self.width*self.height
def __add__(self,other):
return Shape(self.width + other.width,self.height + other.height)
def __gt__(self,comp):
if self.area() > comp.area():
return True
else:
return False
w1 = int(input())
h1 = int(input())
w2 = int(input())
h2 = int(input())
s1 = Shape(w1, h1)
s2 = Shape(w2, h2)
result = s1 + s2
print(result.area())
print(s1 > s2)
def pop(self):
return self._hiddenlist.pop(-1)
def __repr__(self):
return "Queue({})".format(self._hiddenlist)
class Spam:
__egg = 7
def print_egg(self):
print(self.__egg)
s = Spam()
s.print_egg()
though over here we didn’t write s._Spam__egg we still got an output
well that’s because we are not accessing self.__egg directly but through
a method
output: 7
print(s._Spam__egg)
output: 7
print(s.__egg)
output: error the attribute __egg cannot be found
the error was raised because we were trying to access the private
attribute directly and since it is mangled python interpreter was unable to
recognize the attribute
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def calculate_area(self):
return self.width * self.height
@classmethod
def new_square(cls, side_length):
return cls(side_length, side_length)
square = Rectangle.new_square(5)
print(square.calculate_area())
output: 25
over here the class method was accessed directly through the class. It
can be used as an alternative constructor to the __init__
static method
static methods are like class methods but do not have any default
parameters like “cls” or “self”. They cannot modify attributes or
methods in a class like class methods . It can also be used to check a
condition in a class
It is denoted by the static method decorator
class Shape:
def __init__(self,height,width):
self.height = height
self.width = width
@staticmethod
def area(height,width):
return height * width
w = int(input())
h = int(input())
print(Shape.area(w, h))
Wednesday, November 8, 2023
Properties
Properties provide a way of customizing access to instance
attributes.
Example:
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
@property
def pineapple_allowed(self):
return False
class Chicken:
def __init__(self, spices):
self.spices = spices
self._hard = True
@property
def hard_chicken(self):
return self._hard
@hard_chicken.setter
def hard_chicken(self, value):
if value == "hard":
self._hard = value
else:
raise ValueError("Alert! Intruder!")
chicken = Chicken("pepper")
print(chicken.hard_chicken)
chicken.hard_chicken = "hard"
print(chicken.hard_chicken)
the setter command is used on the method hard chicken. The
programmer can set the object chicken to any value as long as the
value is hard then self._hard will be set to that value. But any other
value will raise an error.
Trying to set an object to a value without defining a setter will result
in a error
The setter and getter can also be used on private attributes to
change and retrieve their value
class my_class:
def __init__(self,integer):
self.__integer = integer
def get_integer(self):
return self.__integer
def set_integer(self,a):
self.__integer = a
me = my_class("rainbow")
print(me.get_integer())
me.set_integer("roygbiv")
print(me.get_integer())
the get and set before the methods are the setter and getter
commands. They are used to retrieve and set new values for the
private attribute
Exception handling
A try statement can have multiple different except blocks to handle different
exceptions.
Multiple exceptions can also be put into a single except block using parentheses, to
have the except block handle all of them.
try:
variable = 10
print(variable + "hello")
print(variable / 2)
except ZeroDivisionError:
print("Divided by zero")
except (ValueError, TypeError):
print("Error occurred")
output: Error occurred
You can handle as many exceptions in the except statement as you need.
An except statement without any exception specified will catch all errors. These should
be used sparingly, as they can catch unexpected errors and hide programming
mistakes.
try:
word = "spam"
print(word / 0)
except:
print("An error occurred")
output: An error occured
example
An ATM machine takes the amount to be withdrawn as input and calls the
corresponding withdrawal method.
In case the input is not a number, the machine should output "Please enter a number".
Use exception handling to take a number as input, call the withdraw() method with the
input as its argument, and output "Please enter a number", in case the input is not a
number.
A ValueError is raised when you try to convert a non-integer to an integer using int().
def withdraw(amount):
print(str(amount) + " withdrawn!")
try:
num = int(input())
withdraw(num)
except (ValueError,TypeError):
print("Please enter a number")
The else statement executes code only if the try statement is executed
Try:
Print(4/2)
Except:
Print(‘error’)
Else:
Print(‘it worked’)
Output:
2
It worked
14th November,2023
Raising exceptions
You can throw (or raise) exceptions when some condition occurs.
For example, when you take user input that needs to be in a specific format, you can
throw an exception when it does not meet the requirements.
This is done using the raise statement.
num = 102
if num > 100:
raise ValueError
You need to specify the type of the exception raised. In the code above, we raise a ValueError.
Exceptions can be raised with arguments that give detail about them.
name = "123"
raise NameError("Invalid name!")
This makes it easier for other developers to understand why you raised the exception.
Thursday, November 16, 2023
Working with files
Python can be used to read and write files.
We are starting with text files(extension .txt) because they are easier to
manipulate. When it comes to word files you have to import a special
library to do it.
There is a special function called open and the file name is placed in the
parenthesis
myfile = open("filename.txt")
the file can only be opened like this if it is in the same directory as the
python script used to manipulate it. The open function also takes other
parameters
“r’’ for read mode
“w” for write mode(for rewriting contents of a file)
“a” for append mode, for adding new content to the end of the file
Adding "b" to a mode opens it in binary mode, which is used for non-
text files (such as image and sound files)
Typing a file name in the open function without any additional
parameters it automatically opens the file in read mode
# write mode
open("filename.txt", "w")
# read mode
open("filename.txt", "r")
open("filename.txt")
file = open("/usercode/files/books.txt")
print(file.read(5))
print(file.read(7))
print(file.read())
file.close()
output: Harry
Potter
This will read the first 5 characters of the file, then the next 7.
Calling the read() method without an argument will return the rest of the
file content.
file = open("("/usercode/files/books.txt ", "r")
for i in range(21):
print(file.read(4))
file.close()
output: Harr
y Po
tter
The
Hun
ger
Game
s
Pr
ide
and
Prej
udic
e
Go
ne w
ith
the
Wind
To retrieve each line in a file, you can use the readlines() method to return a list in
which each element is a line in the file.
file = open("/usercode/files/books.txt", "r")
print(file.readlines())
output:
['Harry Potter\n', 'The Hunger Games\n', 'Pride and Prejudice\n', 'Gone with the Wind']
Instead of outputting the lines in the file in a list you can use the for
loop to iterate over each line and also over the file itself
file = open("/usercode/files/books.txt")
file.close()
output:
Harry Potter
file = open("/usercode/files/books.txt")
file.close()
output:
Harry Potter
In case the file already exists, its entire content will be replaced
when you open it in write mode using "w".
If you want to add content to an existing file, you can open it using
the "a" mode, which stand for "append":
file = open("/usercode/files/books.txt", "a")
An alternative way of doing this is by using with statements.This creates a temporary variable
(often called f), which is only accessible in the indented block of the with statement.
with open("/usercode/files/books.txt") as f:
print(f.read())
The file is automatically closed at the end of the with statement, even if exceptions occur within
it.
Example
You are given a books.txt file, which includes book titles, each on a separate line.
Create a program to output how many words each title contains, in the following format:
Line 1: 3 words
Line 2: 5 words
...
Make sure to match the above mentioned format in the output.
To count the number of words in a given string, you can use the split() function, or,
alternatively, count the number of spaces (for example, if a string contains 2 spaces,
then it contains 3 words).
with open("/usercode/files/books.txt") as f:
for n, line in enumerate(f):
print("Line "+str(n+1)+": "+ str(len(line.split()))+" words")
Courses = [‘art’,’maths’,’english’,]
Courses1 = [‘physics’,’chemistry’]
Courses.append(Courses1)
Print(Courses)
Print(Courses[-1])
Output: [‘art’,’maths’,’english’,[‘physics’,’chemistry’]]
[‘physics’,’chemistry’]
List.sort(): it helps rearrange a list in ascending or alphabetical order
Subjects = [‘ict’,’french’,’spanish’]
Numbers = [1,4,2,6,7,9]
Subjects.sort()
Numbers.sort()
Print(Subjects)
Print(Numbers)
Output = [‘french’,’ict’,’spanish’]
[1,2,4,6,7,9]
There is a way to rearrange a list in reverse order (descending)
Subjects = [‘ict’,’french’,’spanish’]
Numbers = [1,4,2,6,7,9]
Subjects.sort(reverse=True)
Numbers.sort(reverse=True)
Print(Subjects)
Print(Numbers)
Output: [‘spanish’,’ict’,’french’]
[9,7,6,4,2,1]
List.reverse(): it rearranges a list in reverse form. It doesn’t necessarily
arrange in descending,ascending or alphabetical order it just reverses the
positions of elements in a list
Names = [‘alice’,’jonathan’,’will’,’eleven’]
Names.reverse()
Print(Names)
Output:[‘eleven’,’will’,’jonathan’,’alice’]
Sorted(): this performs the same function as the sort function but doesn’t
use dot notation. It is used if you do not want to entirely change the
original list. You must store it in a variable and print that variable in
order to see its effect
Animals = [‘owls’,’rabbits’,’dogs’,’tigers’]
Sorted_list = sorted(Animals)
Print(Sorted_list)
Print(Animals)
Output:
[‘dogs’,’owls’,’rabbits’,’tigers’]
[‘owls’,’rabbits’,’dogs’,’tigers’]
output: 1
join(): joins the elements of a list into one string. Uses dot notation and
the first string before the dot is the separator
#course_str = ', '.join(courses)
Print(course_str)
output: “science,math,law,medicine”
split(): converts a group of strings into a list. Uses dot notation and the
separator is typed in the parenthesis
new_list = course_str.split(' , ')
#print(new_list)
output: [‘science’,’math’,’law’,’medicine’]
sets
the set commands |,&,- and ^ also have word alternatives that can be
used instead of the symbols
| [set.union(set)]
my_courses = {'physics','elective maths','biology','chemistry'}
her_courses = {'elective ict','biology','physics','accounting'}
print(my_courses.union(her_courses))
& [set.intersection(set)]
print(my_courses.intersection(her_courses))
output: {“biology”,”physics”}
-[set.difference(set)]
print(my_courses.difference(her_courses))
# Empty Tuples
empty_tuple = ()
empty_tuple = tuple()
# Empty Sets
empty_set = {} # This isn't right! It's a dictionary
empty_set = set()
print(student)
dict.pop():to delete a key with its corresponding value. You can store it
in a variable. And the variable be outputted to return the removed value
age = student.pop('age')
print(age)
output: 25
dict.update(): used to update different keys or values in a dictionary
simultaneously.
student = {'name': 'john','age':25,'courses':['math','compsci'] }
output: {‘name’:’Jane’,’age’:30,’phone’:’555-5555’}
dict.values(): returns only the values in a dictionary
print(student.values())
output:’Jane’,30,’555-5555’
dict.keys(): returns only the keys in a dictionary
print(student.keys())
output: ‘name’,’age’,’phone’
dict.items(): returns the keys and values in a dictionary
print(student.items())
output: {‘name’: ‘Jane’,’age’:30,’phone’:’555-5555’}
look at this
let us say I want to use a for loop to output the keys and values in the
dictionary student and I type this:
for key in student:
print(key)
output: name
age
phone
this code only outputs the keys. If we want to output the key and the
values we have to type this:
for key,value in student.items():
print(key,value)
output:
name Jane
age 30
phone 555-5555
Wednesday, November 29, 2023
Conditionals and Boolean
We now the symbols used in comparison like greater than, less than etc.
Comparisons:
# Equal: ==
# Not Equal: !=
# Greater Than: >
# Less Than: <
# Greater or Equal: >=
# Less or Equal: <=
# Object Identity: is
but there is one we have not quite discussed which is ‘is’. Is determines
if a two values have the same identity in memory. It is slightly different
from the double equal sign. Here is an example to prove that point.
a = [1,2,3]
b = [1,2,3]
print(a == b)
output: True
a =[1,2,3]
b = [1,2,3]
print(a is b)
output: False
the first one outputted
true while the second one outputs false. We are going to show the
reason for this observation by using the id function to show the
identity of the two lists in memory
print(id(a))
print(id(b))
the output of both lists will show different numbers indicating
that they both do not have the same identity in memory.
However I will show another example where the output is True
a =[1,2,3]
b = a
print(a is b)
output: True
if not logged_in:
print('please log in')
else:
print('welcome')
condition = {}
if condition:
print('evaluated to True')
else:
print('evaluated to false')
Condition:
Code1
Break
Code2
Code 1 is executed when the condition is met while code 2 is
executed when the condition is not met
nums = [1, 2, 3, 4, 5]
for num in nums:
if num == 3:
print('Found!')
break
print(num)
output:
1
2
Found!
Continue can be used to skip an iteration when a condition is met.
It uses the same format as the break command
for num in nums:
if num == 3:
print('Found!')
continue
print(num)
ouput:
1
2
Found!
3
4
5
Nested loops
One can store a loop within another loop. Here is an example
for num in nums:
for letter in 'abc':
print(num,letter)
output:
1a
1b
1c
2a
2b
2c
3a
3b
3c
4a
4b
4c
5a
5b
5c
There is another way to iterate over two iterables at the same
time that produces another result different from the nested loop.
One uses the command zip()
for num,letter in zip(nums,'abc'):
print(num,letter)
output:
1a
2b
3c
With the zip command, the iteration stops when the end of the
shortest iterable is reached
Enumerate() is also another loop command but it was already
discussed earlier
While loop
One can use the break and continue in a while loop as well
x = 0
while True:
if x == 5:
break
print(x)
x += 1
output:
0
1
2
3
4
student_info(*courses, **info)