Lectures OOP Python
Lectures OOP Python
Lectures OOP Python
Lecture 1
Installing Python
C:\>cd Desktop\python_work
C:\Desktop\python_work>dir
hello_world.py
C:\Desktop\python_work>python hello_world.py or C:\Desktop\python_work>python
hello_world.py
Hello Python world!
1|Page
– BIOS and CMOS commands (e.g F2 for Dell, F10 for compaq, Esc+F1 for IBM
• Commands to:
– Change directory:CD
– Check date:DATE
– Check time:TIME
– To create a text file: copy con X.x(good for win10) where X is file name and x is extension,
edit X.x, star X.x or echo xxxxx>X.x(good for win 7)
– Rename: rencomand
• Dir/w: presents information using wide format where details are omitted and files and folders are
listed in columns on the screen
• Copy/V: Size of each new file is compared to the size of the original file
• Wild card caracters: ? For one character and * for one or more characters
• Copy command:
• copy c:\myfile.txt d: copy the file "myfile.txt" on the C: drive to the d: drive.
• copy *.txt e: copy all text files in the current directory to the E: drive.
• copy f:\example.xls: copy the file "example.xls" on the F: drive to the current directory.
• Graphics:
• Sounds
• Videos
• Documents
• Hypermedia
Shell scripting
• Ls-a:shows all files and directories including those whose names begin with a . (dot)
Cd /: go to root directory
4|Page
• Cp:copies files and directories
• Echo:print arguments
• Passwd:change password
Wild Cards
– OS Windows_7 running OS
• If you're running Unity: open the dash, type terminal, hit Return.
• Control + Alt + T.
5|Page
Tools
Textblob — processed textual data library tool (already trained on numerous textual data.)
Lecture 2
Basic Syntaxsyntax
assert finally or
6|Page
def if return
elif in while
else is with
5. Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the
same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following are
legal −
6. Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the
end of the physical line are part of the comment and the Python interpreter ignores them
9. Multiple Assignmente.g
a,b,c = 1,2,"john"
A) Numbers
var1 = 1
var2 = 10
Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part
y. x and y are numeric expressions
B) String
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken
using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and
working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator.
str='Hello World!'
%c character
8|Page
%d signed decimal integer
%o octal integer
C) List
Lists are the most versatile of Python's compound data types. A list contains items separated by
commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C.
One difference between them is that all the items belonging to a list can be of different data type
list=['abcd',786,2.23,'john',70.2]
tinylist=[123,'john']
9|Page
Python Expression Results Description
D) Tuple
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be
updated. Tuples can be thought of as read-only lists.
tuple=('abcd',786,2.23,'john',70.2)
tinytuple=(123,'john')
10 | P a g e
('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
D) Dictionary
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but
are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]).
dict={}
dict['one']="This is one"
dict[2]="This is two"
tinydict={'name':'john','code':6734,'dept':'sales'}
e.g
var=100
11 | P a g e
if(var==100):print"Value of expression is 100"
print"Good bye!"
{last_name}" >3.5
EXAMPLES
A )STRINGS
example 1
name = "Ada Lovelace"
print(name.upper()) #To change to upper case
print(name.lower()) #To change to lower case
name = "adalovelace"
print(name.title())#To start with capital letter
example 2
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"#To concatenate names
message = f"Hello, {full_name.title()}!"
print(message)
Underscores in Numbers
When you’re writing long numbers, you can group digits using underscores
to make large numbers more readable:
>>>universe_age = 14_000_000_000
Exercise 1
1. Use a variable to represent a person’s name, and print
a message to that person. Your message should be simple, such as, “Hello Eric,
would you like to learn some Python today?”
2. Use a variable to represent a person’s name, and then print
that person’s name in lowercase, uppercase, and title case.
B) LISTS
example 3
12 | P a g e
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0].title())
print(bicycles[1])
print(bicycles[3])
Exercise 2
1. Store the names of a few of your friends in a list called names. Print
each person’s name by accessing each element in the list, one at a time.
2. Start with the list you used in Exercise 1, but instead of just
printing each person’s name, print a message to them. The text of each message
should be the same, but each message should be personalized with theperson’s name.
Modifying elements
example 4
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
Adding elements
example 5
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
example 6
motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)
INSERTING ELEMENTS
example 7
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
REMOVING ELTS
example 8
13 | P a g e
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
example 9
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
example 10
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
example 11
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
too_expensive = 'ducati'
motorcycles.remove(too_expensive)
print(motorcycles)
print(f"\nA {too_expensive.title()} is too expensive for me.")
example 12
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
example 13
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)
example 14
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
14 | P a g e
PRINTING A LIST IN REVERSE ORDER
example 15
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
example 16
cars = ['bmw', 'audi', 'toyota', 'subaru']
len(cars)
Exercise 3
1. Think of at least five places in the world you’d like tovisit.
• Store the locations in a list. Make sure the list is not in alphabetical order.
• Print your list in its original order. Don’t worry about printing the list neatly,
just print it as a raw Python list.
• Use sorted() to print your list in alphabetical order without modifying the
actual list.
• Show that your list is still in its original order by printing it.
• Use sorted() to print your list in reverse alphabetical order without changing
the order of the original list.
• Show that your list is still in its original order by printing it again.
• Use reverse() to change the order of your list. Print the list to show that its
order has changed.
• Use reverse() to change the order of your list again. Print the list to show
it’s back to its original order.
• Use sort() to change your list so it’s stored in alphabetical order. Print the
list to show that its order has been changed.
• Use sort() to change your list so it’s stored in reverse alphabetical order.
Print the list to show that its order has changed.
Lecture 3
for loop
print("Thank you, everyone. That was a great magic show!") #after the loop
for value in range(1, 5): # to print 1 2 3 4. Not the last value in the range is not printed
print(value)
#even numbers
squares = []
for value in range(1, 11):
square = value ** 2
squares.append(square)
print(squares)
OR
squares = []
for value in range(1,11):
squares.append(value**2)
print(squares)
OR
squares = [value**2 for value in range(1, 11)]
print(squares)
Slicing a List
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3]) #to print from first to third values
print(players[2:])# to print from second and above elt.
print(players[-3:])# to print the last 3 elements. Negative is for last
16 | P a g e
Tuples
dimensions = (200, 50) # Use tuples when you want to store a set of unchangeble values
for dimension in dimensions:
print(dimension)
if Statements
ifconditional_test:
do something
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
else:
price = 40
print(f"Your admission cost is ${price}.")
Dictionaries
17 | P a g e
#adding key value pairs
#Modifying values
Exercise: Using the concept of dictionary, create a key value pair that will will document information
about HIBMAT. it should be such that once the key words appear, the information is displayed. e.g
etc.
Program it in such a way that if the keyword is not found, it will ask if you want to add the pair and you
do so.
input() Function
message = input("Tell me something, and I will repeat it back to you: ") #use terminal to run input
functions
print(message)
18 | P a g e
name = input("Please enter your name: ")
print(f"\nHello, {name}!")
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
print(f"\nThe number {number} is even.")
else:
print(f"\nThe number {number} is odd.")
current_number = 1
whilecurrent_number<= 5:
print(current_number)
current_number += 1
19 | P a g e
Functions
defgreet_user(): #define function
"""Display a simple greeting."""
print("Hello!")
greet_user()#call function
Cl asses
Creating Class
class Dog: #define a class called Dog. By convention, capitalized names refer to classesin Python
"""A simple attempt to model a dog.""" # docstring describing what this class does.
def __init__(self, name, age):
# The __init__() Method, A function that’s part of a class is a method. a special method that Python runs
#automatically whenever we create a new instance. This method has two leading #underscores and two
trailing #underscores
"""Initialize name and age attributes."""
self.name = name #attributes.
self.age = age
def sit(self): #other methods
"""Simulate a dog sitting in response to a command."""
print(f"{self.name} is now sitting.")
defroll_over(self):
"""Simulate rolling over in response to a command."""
print(f"{self.name} rolled over!")
my_dog = Dog('Willie', 6) # instance of a class=object
print(f"My dog's name is {my_dog.name}.") # my_dog.name is to access attribute of an instance, we use
dot notation
print(f"My dog is {my_dog.age} years old.")
my_dog.sit() # calling a method we use dot notation
my_dog.roll_over()
20 | P a g e
"""Print a statement showing the car's mileage."""
print(f"This car has {self.odometer_reading} miles on it.")
my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
my_new_car.odometer_reading = 23 #modify attributes
my_new_car.read_odometer()
Inheritance
class Car: #parent class
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
defget_descriptive_name(self):
long_name = f"{self.year} {self.manufacturer} {self.model}"
returnlong_name.title()
defread_odometer(self):
print(f"This car has {self.odometer_reading} miles on it.")
defupdate_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
defincrement_odometer(self, miles):
self.odometer_reading += miles
classElectricCar(Car): #Child class i.e inheritance
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
Initialize attributes of the parent class.
Then initialize attributes specific to an electric car.
"""
super().__init__(make, model, year)
self.battery_size = 75 #attributes for a child class
defdescribe_battery(self):
"""Print a statement describing the battery size."""
print(f"This car has a {self.battery_size}-kWh battery.")
my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
Importing classes
from car import Car# where car is the file name e.g car.py and Car is the class name
import car # i.e import an entire file
fromelectric_car import ElectricCar as EC# using alias
21 | P a g e
HIBMAT Buea
Python CA:
Lecturer: Mr. Ngolah
Presentation: last class of January
Tasks:
1) Create an app to be used in a newly created snack bar in town. The app should be such
that it takes the number of bottles and calculate the bill. You can optionally make
provision for the printing of the receipt or not.
** check sample below
2) Create an app to be used in HIBMAT as a dictionary. The app should be able to define
the concepts very common in the institution
3) Design a simple game that can be used in software engineering club.
e.g *** a game to guess the right number
22 | P a g e