In Python, everything is an object.A class helps us create objects.
Creating a Class
Use the class keyword to create a class
class Person: first_name ="Betty" last_name ="Kawala" age =30## Instantiating a class# Now we can ceate an object from the class by instantiating it.# To instantiate a class, add round brackets to the class name.person_obj1 = Person()type(person_obj1)
The super() and __init__ functions found in the Dog class allow us to inherit the properties and methods of the Animal class.
Parent and Child Class
The parent class is the class from whick the other class inherits from.
The child class is the the class that inherits from another class
In our example above, the Animal is the parent class while the Dog class is the child class
More Class and Inheritance Examples
Animal
class Animal:def__init__(self, name, sound):self.name = name self.sound = sounddef speak(self):print(self.name +' is '+self.sound +'ing')class Dog(Animal):def__init__(self, name, sound):super().__init__(name, sound)def walk(self):print( self.name +' is '+'walking...')# returnclass Snake(Animal):def__init__(self, name, sound):super().__init__(name, sound)def crawl(self):print(self.name +' is '+'crawling..')snake1 = Snake(name='Sensei', sound='Hiss')snake1.speak()
Sensei is Hissing
Library
class Library:def__init__(self, name):self.name = nameself.books = [] # list of booksself.lent_books = [] # list of lent books# add book to the librarydef addBook(self, book):self.books.append(book) # add many books to the librarydef addManyBooks(self, books):self.books.extend(books)# display books in the librarydef displayBooks(self):for book inself.books:print(book)# lend book to a persondef lendBook(self, title, person):for book inself.books:if book.title == title:if book.title notinself.lent_books: person.borrowed_books.append(book)self.lent_books.append(book.title)returnelse:print(title +' is not availabe')returnprint('There no such book in the library') def__str__(self):returnstr(self.name)
class Book:def__init__(self, title, author):self.title = title self.author = authorself.available =Truedef__str__(self):returnstr(self.title)
class Person:def__init__(self, name):self.name = nameself.borrowed_books = [] # list of borrowed books# display all borrowed booksdef displayBooks(self):for book inself.borrowed_books:print(book)def__str__(self):returnstr(self.name)
# create our booksour_books = [ Book(title='Song of Lawino', author="Okot p'Bitek"), Book(title='Da Vinci Code', author='Dan Brown'), Book(title='Harry Potter', author='JK Rowling')] # add books to the librarystat_library.addManyBooks(books=our_books)
# display available books in the librarystat_library.displayBooks()
Song of Lawino
Da Vinci Code
Harry Potter
# lend out book stat_library.lendBook(title='Harry Potter', person=betty)
# lend out bookstat_library.lendBook(title='Song of Lawino', person=betty)
# display books borrowed by Bettybetty.displayBooks()
Harry Potter
Song of Lawino
# display all lent out booksstat_library.lent_books
['Harry Potter', 'Song of Lawino']
# try lending out an already lent bookstat_library.lendBook(title='Song of Lawino', person=viola)
Song of Lawino is not availabe
# lend out bookstat_library.lendBook(title='Da Vinci Code', person=viola)
# try lending out non existent bookstat_library.lendBook(title='Angels and Demons', person=shafara)
There no such book in the library
Formatted Strings
statement ='{} loves to code in {}'formatted = statement.format('Juma', 'JavaScript')print(formatted)
Juma loves to code in JavaScript
name ='Juma'; language ='JavaScript'statement =f'{name} loves to code in {language}'print(statement)
Juma loves to code in JavaScript
answer =f'The summation of 5 and 7 is {5+7}'print(answer)
The summation of 5 and 7 is 12
# Using indexesname ='Juma'language ='javascript'statement =f'{name} loves to code in {language}'modified = statement.format(language='JavaScript', name='Juma')print(modified)
Juma loves to code in javascript
name ='Viola'fruit ='orange'expression ='so much'# positional formatingstatement ='{} loves my {}'.format(name, fruit)print(statement)
Viola loves my orange
# indexingstatement ='{0} loves my {1}'.format(name, fruit)print(statement)
Viola loves my orange
try…except
# try:# statements# except:# statementsdef dataideaArithmetic(x, y, operation):if operation =='+':return x + yelif operation =='-':return x - yelif operation =='/':return x / y else:return x * y
print(''' DATAIDEA Arithmects:Instructions-------------------------Enter only two numbers and the operation as +, -, /, x''')# number1 = float(input('Enter first number: '))# number2 = float(input('Enter second number: '))# operator = input('Enter the operator: ')try: answer = dataideaArithmetic(number1, number2, operator)print(f'{number1}{operator}{number2} = {answer}')except:print('A problem occured while running the operation')else:print('Your code has run successfully!')finally:print('Code execution complete.')try:# age = input('Enter your age: ') age ='32' age_integer =int(age)if age_integer >=18:print('Your vote has been cast')else:print('You are not eligible to vote')exceptValueError:print('A problem occured while picking your age \n''You did not enter a number')else:print('Thanks for participating!')
DATAIDEA Arithmects:
Instructions
-------------------------
Enter only two numbers and the operation as +, -, /, x
2.022.0 = 4.0
Your code has run successfully!
Code execution complete.
You are not eligible to vote
Thanks for participating!
# Creating your own errorstry: # age = int(input('Enter your age: ')) age =''if age <18:raiseException('Not an adult')exceptExceptionas error:print('A problem occurred \n'f'Error: {error}')
A problem occurred
Error: '<' not supported between instances of 'str' and 'int'
Variable Scope
# local scope# a variable that is created/defined # inside a function has a local scope# create a fucntion that greats people# - All variable declared outside a function globalname ='Voila'def my_func():global my_fruit my_fruit ='orange'# print(name + ' loves my ' + my_fruit)my_func()print(my_fruit)
orange
number =45# defined outside a function# can be accessed hereprint(number)def getSquare():# can also be accessed hereprint(number **2)getSquare()
45
2025
#Local Scopedef add(): number1 =5 number2 =7 summ = number1 + number2return summ# print(add())try: print(summ)except:print("summ is not defined")