You are on page 1of 82

Programming: python

Python beginner
15th august, 2023

 Python is a programming language that uses simple words that


humans can understand
 Python is used for creating web applications, designing gaming
software, and used in data science
 It consists of variables that contain values
 Variables are usually one word
 To write more than one word, introduce underscore _ to separate
the words
 Variables can contain values
 Values are written in double quotes and introduced by an equal to
sign
 This data type is called a string
 To display data as output the print command is used
 It is a predefined command in python language
 Print()
 The variable or value typed in the parenthesis is displayed in the
console
 The console is where the data is displayed
 When typing values in the parenthesis introduce the double quotes
 But do not introduce quotes when typing variables
 NB: typing variables to print does not display the variable but the
value it contains

16th august, 2023.



 Python can also be used for calculation
 Numbers can be used to perform addition +, subtraction -, multiplication*
and division /.
 The numbers are not placed in double quotes because they are not strings
 Strings are not used for calculations

17th august, 2023


 Boolean (true or false)
 Python also has a data type with the options true or false
 True is used to indicate that a feature is on
 False is used to indicate if a feature is off
 They are not strings therefore are not typed in double quotes

Wednesday, August 23, 2023


 One can use python to demand input from a user

 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

Thursday, August 24, 2023


 A programmer can use code to determine the data type of a value stored in a
variable
 The programmer types type() and types the variable name in the parenthesis
 You can also display the data type of the variable by typing print(type())
 The input of a variable is automatically stored as a string
 But one can change the data type of an input
 Name=input()
 Print(type(Name))
 #data type is string
 Name=int(input())
 Print(type(Name))
 #data type is integer
 Name=float(input())
 Print(type(name))
 #data type is float
 Height=str(input())
 Print(type(height))
 #data type is string
 Strings cannot be used for calculations but using the plus sign will join
strings
 A=”3”
 B=”7”
 Print(A+B)
 #output will be 37

Saturday, August 26, 2023


 Comparison in python
 Computers use a data type called Boolean to perform complex operations
 A programmer can use the greater than or less than sign to tell the computer
what to do
 The comparison can either be true or false
 I said earlier that Boolean can be used to turn a feature on or off
 These logical comparisons can be used to tell a computer what to do
 Example
 A game will only allow a player to level up if his score is more than a
hundred
 Score=int(input())
 #the input must be an integer because strings cannot be used for operations
 Print(score>100)
 If the input is indeed more than 100 the output will be true and the player
will move on to the next level
 Computer stores converts data into simple forms so it can easily perform
operations
 This is known as binary code
 It acts as a form of switch with 1 meaning on or true and 0 meaning off or
false
 Multiple Boolean inputs can be fed into a computer but it outputs only one
Boolean
 True and true outputs true
 True and false outputs false
 True or false outputs true

Monday, August 28, 2023


 Computers have different ways of completing tasks
 Sequencing: from one line to another
 Iteration: repeats certain tasks
 Selection: follows a certain path
 A programmer can represent a combination of these ways in a set of
instructions called algorithm

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

Lists are mutable meaning you can change a value in list


Movies=[“titanic”,”Inception”,”quiet place”]
Movies[0]=lovely bones
Print(movies[0])
Output is lovely bones
The Strings too are represented by indices
E.g.
012
Animals=“c a t”
Print(animals[1])
Output: a
Unlike lists characters in a string are immutable
In indexing space is also recognized
Wednesday, September 6, 2023

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

Everything above also applies with strings

Tuesday, September 12, 2023

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

Thursday, September 21, 2023


The argument can also be used to perform more than one function which are
illustrated after the colon and indented like the index
Def plot_of_land(d1, d2):
Area=d1*d2
Perimeter=2*d1+2*d2
Return area,perimeter
More than one variable can store different values on the same line but they must
correspond
Ar,per=plot_of_land(5,3)
Print(ar,per)
Output= 15(area of plot), 16(perimeter of plot)
The output is in this order because the return was in the order area,perimeter and
the area is stored in the first variable(ar) and the perimeter is stored in the 2 nd
variable(per)
The index can also a boolean(logical operation)
Def house_suitability(cost,area):
Cost=cost<350,000
Area=area>400

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

You can set a function to a default value when nothing is inputed


Def greet(name=friend):
Print(“welcome”,name)
Greet()
Output: welcome,friend. This is because there was no input for the name so the
computer outputted the default value friend

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

Get is a dictionary function used to output an item in a dictionary by inputting the


key and the second value after the comma is outputted if the key is not in the
dictionary
Print(designerclothes.get(1,8))
Output: “Gucci”
Print(designerclothes.get(“Dior”,”not available”))
Output: true
Print(designerclothes.get(“Chanel”,”not available”))
Output: not available
This is because the first value wasn’t available so it output’s the second value
Print(designerclothes.get(input(),”not available”)
This code takes a key as input and searches through the dictionary and if it is not
there it outputs “not available”

Tuesday, September 26, 2023

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

Wednesday, September 27, 2023


Tuples can also store lists,dictionaries and lists can also store tuples,dictionaries
and dictionaries can also store lists and tuples

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

Wednesday, September 27, 2023

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

Friday, September 29, 2023

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

Numbers=[i*2 for i in range(10)]


Print(Numbers)
This will produce a loop from 0 to 10 and multiply each number by 2
NB: two asterisk mean raised to a power **
Output: 0,2,4,6,8,10,12,14,16,18,20

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

You can set a range to output between certain numbers


For i in range(3,9)
Output: 3,4,5,6,7,8

Tuesday, October 10, 2023

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)

print(my_func(lambda x: 2*x*x, 5))


output: 100

maps and filters


maps perform an iteration and performs the specified operation on each
item in a list or other iterables
example
def add_five(x):
return x + 5
nums = [11, 22, 33, 44, 55]
result = list(map(add_five, nums))
print(result)

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

initial_salaries = [2000, 1800, 3100, 4400, 1500]


bonus = int(input())
def new_salaries(x):
return x + bonus
salaries = list(map(new_salaries,initial_salaries))
print(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

Saturday, October 14, 2023


Generators
Generators are iterators and use functions to iterate. They can use for
loop and while loop. Generators are used when iterating large amount
of numbers without storing everything in memory. It is a way of
iterating without creating a list to avoid using up too much memory to
make the process execute quicker.

The while loop is used in generators when the iteration is going to be


infinite or you want to add up numbers or reduce numbers
Example 1
When you want to use a generator and the while loop to add up
numbers
Def adding_up_numbers():
i=2
while i > 0:
yield i
i +=1
for i in adding_up_numbers():
print(i)
output: it will produce an iteration starting from 2 and keep adding 1 till
infinity
generators are a little like creating functions except you use yield
instead of return
the (for i in adding_up_numbers(): ) is important because
print(i)
without it a generator object will be the output, not an iteration. If you
would like to produce an iteration without the for loop you have to use
the next function
Def adding_up_numbers():
i=2
while i > 0:
yield i
i +=1
print(next(adding_up_numbers()))
output: 2
print(next(adding_up_numbers()))
output:3

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

while loop generator to create an infinite loop


def infinite_number():
while True:
yield 7
for i in infinite_number():
print(i)
output: this will create an infinite iteration of the number seven

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

a generator can also use another function to iterate


def multiples_of_three(h):
if h%3 == 0:
return True
def generator(b):
for i in range(b):
if multiples_of_three(i):
yield i
for i in generator(20):
print(i)
output: 3,6,9,12,15,18

the result of a generator can be converted into a list but turning


it into a list defeats the purpose of a generator because a list stores all
the results in memory unlike generators
def numbers(x):
for i in range(x):
if i % 2 == 0:
yield i

print(list(numbers(11)))
output:[0,2,4,6,8,10]

remember list comprehensions, well you can use list comprehension to


form generators by enclosing the comprehension in parenthesis

again = (s for s in range(10) if s% 2 == 0)


for i in again:
print(i)
NB: the for loop is necessary to make an iteration without it a generator
object will be produced

Monday, October 16, 2023


Decorator
This is a form of functional programming where the decorator(def
decor()) is used to decorate a function
Def decor(func):
Def wrap():
Print(‘-----‘)
Func()
Print(‘-----‘)
Return wrap

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

Instead of typing this: text = decor(text)


text()
or Decorated = decor(text)
Decorated()
You can use the @ symbol to avoid typing this
Def decor(func):
Def wrap():
Print(‘-----‘)
Func()
Print(‘-----‘)
Return wrap

@decor
Def text():
Print(‘hello’)

text();

Output: -----
Hello
-----

If your decorated function requires an argument you must include the


argument in the decorator

Def decor(func):
Def wrap(name):
Print(‘-----‘)
Func(name)
Print(‘-----‘)
Return wrap
@decor
Def text(name):
Print(‘hello’,name)

text(‘helen’);

Output: -----
Hello,helen
-----

Thursday, October 19, 2023


Recursion
Recursion is used when a function calls itself within itself. It is used to
create factorials and mathematics sequences like the Fibonacci
sequence. Recursion uses something called the base case that tells the
function when to stop calling itself to avoid an infinite recursion

Factorial example
def factorial(x):
if x <= 1:
return x
else:
return x * factorial(x-1)
print(factorial(5))
output: 120

what really happened is this:


5*24=120
4*6=24
3*2=6
2*1=2
1*1 = 1
The if statement: if x<=1 is setting the base case to be 1

Now here is an example using recursive functions to generate


Fibonacci numbers
def fibonacci(a):
if a <= 1:
return a
else:
return fibonacci(a - 1) + fibonacci(a - 2)

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

Sunday, October 22, 2023


*args and **kwargs
*args and **kwargs are special commands used in functional
programming
*args
*args are used when you want to make a function accept an infinite
number of arguments.
Example
This function will take num as an argument and *args and compare
num with the maximum number in args and return the highest number
Def numbers(num,*args):
If num>max(args):
Return num

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

Here is another example where *args is used in a function so that it can


return numbers in args which are in a particular range as the other
argument

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

print(func(name = 'alice', age = 34, city = ‘paris’))


key value key value key value
output:
{name: alice,
Age:34,
City:paris}
NB: the key cannot be an integer and do not write the key as a string(no
double or single quotes) this will result in an error

There is a way to use the kwargs to output something like a dictionary


but it is not because the curly brackets , commas and colons will not be
seen in the output

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

NB: it is not compulsory to write *args or **kwargs you can replace it


with any word but the single or double asterisk before the word helps
the computer know whether u r using the args command or the kwargs
command

Object oriented programming

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)

The __init__ method is the most important method in a class.


This is called when an instance (object) of the class is created, using the
class name as a function.

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.

Instances of a class have attributes, which are pieces of data associated


with them.

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.

In an __init__ method, self.attribute can therefore be used to set the


initial value of an instance's attributes.

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.

Classes can have other methods defined to add functionality to them.

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

Thursday, October 26, 2023


Inheritance
In python classes can inherit attributes or methods from other classes.
The classes that are inherited from are called super classes whereas the
classes inheriting from the super class are called sub classes. The
subclasses inherit the superclasses by placing them in parenthesis after
declaring the subclass
class Animal:
def __init__(self, name, color):
self.name = name
self.color = color

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

husky = Dog("Max", "grey")


husky.bark()
output: woof
instead of outputting “Grr…” as stated in the super class the subclass’s
method overrides the superclass’s method

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.

They are used to create functionality that can't be represented as a


normal method.

One common use of them is operator overloading.

This means defining operators for custom classes that allow operators
such as + and * to be used on them.

An example magic method is __add__ for +.

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.

More magic methods for common operators:

__sub__ for -

__mul__ for *

__truediv__ for /

__floordiv__ for //

__mod__ for %
__pow__ for **

__and__ for &

__xor__ for ^

__or__ for |

The expression x + y is translated into x.__add__(y).

However, if x hasn't implemented __add__, and x and y are of different


types, then y.__radd__(x) is called.

There are equivalent r methods for all magic methods just mentioned.
class SpecialString:
def __init__(self, cont):
self.cont = cont

def __truediv__(self, other):


line = "=" * len(other.cont)
return "\n".join([self.cont, line, other.cont])
spam = SpecialString("spam")
hello = SpecialString("Hello world!")
print(spam / hello)
output: spam
============
Hello world!
In the example above, we defined the division operation for our class
SpecialString.
Python also provides magic methods for comparisons.

__lt__ for <

__le__ for <=

__eq__ for ==

__ne__ for !=

__gt__ for >

__ge__ for >=

If __ne__ is not implemented, it returns the opposite of __eq__.


There are no other relationships between the other operators.

class SpecialString:

def __init__(self, cont):

self.cont = cont

def __gt__(self, other):

for index in range(len(other.cont)+1):

result = other.cont[:index] + ">" + self.cont

result += ">" + other.cont[index:]

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.

__len__ for len()

__getitem__ for indexing

__setitem__ for assigning to indexed values

__delitem__ for deleting indexed values

__iter__ for iteration over objects (e.g., in for loops)

__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 __getitem__(self, index):

return self.cont[index + random.randint(-1, 1)]

def __len__(self):

return random.randint(0, len(self.cont)*2)

vague_list = VagueList(["A", "B", "C", "D", "E"])

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)

Saturday, November 4, 2023


Data hiding
This is used in object oriented programming to make private methods
and attributes in a class that cannot be accessed by external code
Weakly private methods or attributes have a single underscore at the
beginning. It signals that it is private and shouldn’t be used by external
code but is just a convention and external code can use it
class Queue:
def __init__(self, contents):
self._hiddenlist = list(contents)

def push(self, value):


self._hiddenlist.insert(0, value)

def pop(self):
return self._hiddenlist.pop(-1)

def __repr__(self):
return "Queue({})".format(self._hiddenlist)

queue = Queue([1, 2, 3])


print(queue)
output: Queue([1, 2, 3])
queue.push(0)
print(queue)
output: Queue([0, 1, 2, 3])
queue.pop()
print(queue)
output: Queue([0, 1, 2])
print(queue._hiddenlist)
output: [0, 1, 2]
NB : the __repr__ is just used to indicate how the string should be
represented in the output and
“Queue({})”.format(self._hiddenlist)
Is the same as f”Queue({self._hiddenlist})”
Strongly private methods and attributes are however preceded by a
double underscore. This causes their names to be mangled and therefore
cannot be accessed outside of the class.
It is done to ensure they are private and prevent bugs with subclasses
that have methods or attributes with the same names
Name mangled methods can still be accessed externally, but by a
different name. The method __privatemethod of class Spam could be
accessed externally with _Spam__privatemethod.

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

Monday, November 6, 2023


Class methods and static methods
Class methods
The methods that we have learned so far use the self parameter. But
class methods do not use the self parameter but the “cls” parameter.
They are denoted by a classmethod decorator. They are used when one
wants to modify an attribute in a class

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.

They are created by putting the property decorator above a method,


which means when the instance attribute with the same name as the
method is accessed, the method will be called instead.

One common use of a property is to make an attribute read-only.

Example:
class Pizza:
def __init__(self, toppings):
self.toppings = toppings

@property
def pineapple_allowed(self):
return False

pizza = Pizza(["cheese", "tomato"])


print(pizza.pineapple_allowed)
output: False
because we used the property decorator when calling the method we
didn’t have to type the parenthesis after the method
Properties can also be set by defining setter/getter functions.

The setter function sets the corresponding property's value.

The getter gets the value.

To define a setter, you need to use a decorator of the same name as


the property, followed by a dot and the setter keyword.

The same applies to defining getter functions.

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

Thursday, November 9, 2023


exceptions
You have already seen exceptions in previous code. They occur when something goes
wrong, due to incorrect code or input. When an exception occurs, the program
immediately stops.
The following code produces the ZeroDivisionError exception by trying to divide 7 by
0:
num1 = 7
num2 = 0
print(num1/num2)
output: Traceback (most recent call last):
File "./Playground/file0.py", line 3, in <module>
print(num1/num2)
ZeroDivisionError: division by zero
An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program.

Different exceptions are raised for different reasons.


Common exceptions:
ImportError: an import fails;
IndexError: a list is indexed with an out-of-range number;
NameError: an unknown variable is used;
SyntaxError: the code can't be parsed properly;
TypeError: a function is called on a value of an inappropriate type;
ValueError: a function is called on a value of the correct type, but with an inappropriate
value.

Exception handling

When an exception occurs, the program stops executing.


To handle exceptions, and to call code when an exception occurs, you can use
a try/except statement.
The try block contains code that might throw an exception. If that exception occurs, the
code in the try block stops being executed, and the code in the except block is run. If no
error occurs, the code in the except block doesn't run.
try:
num1 = 7
num2 = 0
print (num1 / num2)
print("Done calculation")
except ZeroDivisionError:
print("An error occurred")
print("due to zero division")
output: An error occurred
due to zero division
As the code produces a ZeroDivisionError exception, the code in the except block is
run.
In the code above, the except statement defines the type of exception to handle (in our
case, the ZeroDivisionError).

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

Friday, November 10, 2023


finally,else
the finally executes a code, no matter if the try statement is executed
or not
try:
print(2/0)
except ZeroDivisionError:
print(an error occurred)
finally:
print(Bye)
output:
an error occurred
Bye

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

# binary write mode


open("filename.txt", "wb")
once a file is opened you must remember to close it
by using the close function
file = open("filename.txt", "w")
# do stuff to the file
file.close()
reading files
The contents of a file that has been opened in text mode can be read
using the read method.

We have created a books.txt file on the server which includes titles of


books. Let's read the file and output the content:
file = open("/usercode/files/books.txt")
cont = file.read()
print(cont)
file.close()
output: Harry Potter
The Hunger Games
Pride and Prejudice
Gone with the Wind
To read only a certain amount of a file, you can provide the number of
bytes to read as an argument to the read function.

Each ASCII character is 1 byte:

file = open("/usercode/files/books.txt")
print(file.read(5))
print(file.read(7))
print(file.read())
file.close()
output: Harry
Potter

The Hunger Games


Pride and Prejudice
Gone with the Wind

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

for line in file.readlines():


print(line)

file.close()
output:
Harry Potter

The Hunger Games

Pride and Prejudice

Gone with the Wind

file = open("/usercode/files/books.txt")

for line in file:


print(line)

file.close()
output:
Harry Potter

The Hunger Games

Pride and Prejudice


Gone with the Wind

Friday, November 17, 2023


Writing files
To write to files you use the write method.
file = open("newfile.txt", "w")
file.write("This has been written to a file")
file.close()

file = open("newfile.txt", "r")


print(file.read())
file.close()
output: This has been written to a file
This will create a new file called "newfile.txt" and write the content
to it.

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

file.write("\nThe Da Vinci Code")


file.close()

file = open("/usercode/files/books.txt", "r")


print(file.read())
file.close()
output: Harry Potter
The Hunger Games
Pride and Prejudice
Gone with the Wind
The Da Vinci Code
This will add a new line with a new book title to the file.

Remember, \n stands for a new line.


The write method returns the number of bytes written to a file, if
successful.
msg = "Hello world!"
file = open("newfile.txt", "w")
amount_written = file.write(msg)
print(amount_written)
file.close()
output: 12
The code above will write to the file and print the number of bytes
written.

To write something other than a string, it needs to be converted to a


string first.
Example:
Take a number N as input and write the numbers 1 to N to the file "numbers.txt", each
number on a separate line.
Sample Input
4
Sample Output
1
2
3
4
The given code reads the content of the file and outputs it.
You can use \n to make line breaks.
Do not forget to close the file after writing to it.
n = int(input())

file = open("numbers.txt", "w+")


for i in range(1,n+1):
file.write(str(i)+"\n")
file.close()
f = open("numbers.txt", "r")
print(f.read())
f.close()

Sunday, November 19, 2023

Working with Files


It is good practice to avoid wasting resources by making sure that files are always
closed after they have been used. One way of doing this is to use try and finally.
try:
f = open("/usercode/files/books.txt")
cont = f.read()
print(cont)
finally:
f.close()
output: Harry Potter
The Hunger Games
Pride and Prejudice
Gone with the Wind

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

Python Beginner Revision


Strings
More string functions:
Str.replace(“”,””): to replace a word or letter in a string or group
of strings. The first space takes the old string and the second
space takes the new string.
Str.count(): to determine how many times a letter or word
appears in a string

Dir(): this is not designated for only strings but any


function,variable,class,data type or data collection type can be
typed in the parenthesis and it will output the commands that can
be used on it
Help(): this is also not only used for strings but any function or
command typed in the parenthesis the help function describes its
uses
Monday, November 20, 2023
Integers and floats
Round(): it is a function that rounds a float or integer to the nearest
integer. It can also take another argument where you can determine what
place it should round to.
Print(round(3.75))
Output: 4
Print(round(3.75,1))
Output: 3.8
Lists
List.extend(): works like append. It is preferred if you want to add a list
to another list but don’t want the added list to be added as a single
element in the list.
Courses = [‘art’,’maths’,’english’,]
Courses1 = [‘physics’,’chemistry’]
Courses.extend(Courses1)
Print(Courses)
Print(Courses[-1])
Output: [‘art’,’maths’,’english’, ‘physics’,’chemistry’]
chemistry

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’]

Wednesday, November 22, 2023


List functions
Sum(): as the name suggests it adds up all the elements in a list
List.index(): returns index of element in the parenthesis. Uses dot
notation
courses = ['science','math','law','medicine']
print(courses.index('math'))

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

output: {‘physics’,’elective maths’,’biology’,’chemistry’,’elective


ict’,’accounting’}

& [set.intersection(set)]
print(my_courses.intersection(her_courses))

output: {“biology”,”physics”}
-[set.difference(set)]
print(my_courses.difference(her_courses))

output: {‘elective ict’,’accounting’}


notes on the function enumerate()
this function is used on any iterable like lists,sets and tuples. It acts like
a for loop. It outputs the index and the corresponding element in an
iterable
courses = ['science','math','law','medicine']

for index,course in enumerate(courses):


print(index,course)
the index value outputs the index and the course is the value that
represents the items in the iterable. The iterable being used is in the
enumerate parenthesis
output:
0 science
1 math
2 law
3 medicine
We can also set the starting index if we don’t want it to start at 0
for index,course in enumerate(courses,start=1):
print(index,course)
output:
1 science
2 math
3 law
4 medicine

Just a few extra notes


# Empty Lists
empty_list = []
empty_list = list()

# Empty Tuples
empty_tuple = ()
empty_tuple = tuple()

# Empty Sets
empty_set = {} # This isn't right! It's a dictionary
empty_set = set()

Friday, November 24, 2023


Dictionaries
Functions for dictionaries
Del : to delete a key with its corresponding value
student = {'name': 'john','age':25,'courses':['math','compsci'] }
del student['name']

print(student)

output: {‘age’:25,’courses’: [‘math’,’compsci’]}

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'] }

student.update({'name': 'Jane','age': 30,'phone': '555-5555'})

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

there is a command called “not” that changes a Boolean to its


opposite values,so True becomes False and False becomes True
user = 'admin'
logged_in = False

if not logged_in:
print('please log in')
else:
print('welcome')

output: ‘please log in’

some values are automatically set to false so when used in an if


statement, the first condition will not be fulfilled but rather the
else condition.
# False Values:
# False
# None
# Zero of any numeric type
# Any empty sequence. For example, '', (), [].
# Any empty mapping. For example, {}.

condition = {}
if condition:
print('evaluated to True')
else:
print('evaluated to false')

Output: evaluated to false

Tuesday, December 26, 2023


Iterations and loops
Break and continue
Break is a statement used to stop an iteration when a certain
condition is met the format is like this

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

Friday, December 29, 2023


Args and kwargs
We learnt args and kwargs earlier. And the fact that args has 1
asterisk before it while kwargs has 2. If you want to enter
arguments for both args and kwargs and they are stored in a
variable. You bring one asterisk before the variable for args and
two asterisks for the variable for kwargs
def student_info(*args,**kwargs):
print(args)
print(kwargs)
courses = ['math','art']
info = {'name': 'henry cavill','age': 30}

student_info(*courses, **info)

You might also like