0% found this document useful (0 votes)
4 views20 pages

Python Programming

Python is a versatile, high-level programming language known for its ease of learning, rich libraries, and strong community support. It supports various programming paradigms, including object-oriented and functional programming, and is widely used in applications such as web development, data analysis, and machine learning. Key concepts covered include variables, data types, operators, and control structures, along with specific features like strings, lists, and tuples.

Uploaded by

stephenpelummy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views20 pages

Python Programming

Python is a versatile, high-level programming language known for its ease of learning, rich libraries, and strong community support. It supports various programming paradigms, including object-oriented and functional programming, and is widely used in applications such as web development, data analysis, and machine learning. Key concepts covered include variables, data types, operators, and control structures, along with specific features like strings, lists, and tuples.

Uploaded by

stephenpelummy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Programming

Python is general purpose, high level language, interpreted, dynamically typed programming
language developed by Guido Van Rossum.
Why Python?
1. Easy to understand and learn
2. Free and open source language
3. Fewer code lines, less time
4. Approved by Data Scientists
5. Python has a huge community.
Features of python
1. Object oriented
2. Cross platform
3. Rich Libraries
4. Simple to use
5. Integrable
6. Elegant syntax
Applications of python
1. Web applications
2. Data Analysis
3. Machine Learning
4. Game Development
5. Automation
Variable
A variable in programming is a named storage location that hold data, which can change
during program execution.
Value: The actual data stored.
An assignment statement creates new variables and gives them values
name = “Paul”
salary = 5000
Multiple Assignment
a = 10
b = 10
c = 10
a = b =c= 10
x = 20
y = 30
z = 40
x, y, z = 20, 30, 40
print (y, z)
Python Tokens
Token are smallest meaningful components
1. Keywords
2. Identifiers
3. Literals
4. Operators
What are keywords?
 Python keywords are special reserved words
 Convey special meaning to compiler/interpreter
 Each keyword has a special meaning and a specific operation
 NEVER use it as a variable
It turns out that class is one of Python’s keywords. The interpreter uses keywords to
recognize the structure of the program, and they cannot be used as variable names.
Python 2 has 31 keywords:
and del from not while as elif global or with assert else if
pass yield break except import print class exec in raise
continue finally is return def for lambda try In
Python 3, exec is no longer a keyword, but nonlocal is.

Identifiers
What are identifiers?
Identifiers are the name used to identify a variable, function, class or an object.
RULES defined for naming an Identifiers:
 No special character except underscore (_) can be used as an identifier
 Keyword should not be used as an identifier name
 Python is a case sensitive, i.e Var and var are two different identifier
 First character of an identifier can be character, underscore (_) but not digit
Literals
Literals are constant used in pythons
 String Literals
 Numeric Literals
 Boolean Literals
 Special Literals
String Literals
String literals are formed by enclosing text in a quote. Both single quotes and double quotes
can be used.
Example
name1 = “John”
name2 = “James”
print(name1)
Numeric Literals
 Int: –ve and +ve numbers (integers)
 Long: unlimited integer size followed by upper or Lowercase L
 Float: Real numbers with both integer and fractional part ex: 3.14
 Complex: In the form of a+bj. ‘a’ forms the real part and be the imaginary part. Ex:
3.134j
In python, value of an integer is not restricted by the number of bits and can expand to the
limit of the available memory
No special arrangement is required for storing large numbers.
What are Booleans Literals?
Can have only two values:
 True
 False
What are special Literals?
Python has one special literal: None. It is used to specify to the field that is not created
Example: Value1 = 2
Value2 = None
Print (value1)
Operators and operands
Operators are special symbols that represent computations like addition and
multiplication. The values the operator is applied to are called operands. The operators +,
-, *, / and ** perform addition, subtraction, multiplication, division and exponentiation.
Types of Operators
1. Arithmetic Operator
2. Assignment Operator
3. Comparison Operator
4. Logical Operator
5. Bitwise Operator
6. Identify Operator
7. Membership Operator
Arithmetic Operator: takes two operands to perform operations on them. +, -, *, /, %
e.g. 1 + 2, 1 – 2
The + operator works with strings, but it might not do what you expect: it performs
concatenation, which means joining the strings by linking them end-to-end. For example:
first = 'throat' second = 'warbler' print first + second The output of this program is
throatwarbler. The * operator also works on strings; it performs repetition. For example,
'Spam'*3 is 'SpamSpamSpam'. If one of the operands is a string, the other has to be an
integer
Assignment Operator: assign a value to a variable
=, +=, -=, *=
Comparison Operator
Compare two values and returns true or false as output.
<, >, <=, >=, !=
Logical Operator
Performs logical operation and returns true or false as output.
and, or, not
Bitwise Operator
Used to perform bitwise calculation

Operator Symbol How it works


AND & 1 if both bits are 1
OR | 1 if at least one bit is 1
XOR ^ 1 if bits are different
NOT ~ Flip bits
Left Shift << Moves bits left, fill with 0
Right Shift >> Moves bit right , drop last
bit

Why Use Bitwise?


1. Efficiency: Faster than arithmetic operation in low-level programming
2. Graphics programming (color manipulation)
3. Cryptography (XOR for encryption)
4. Competitive programming (checking parity, power of 2 etc.)
5. Hardware control (flags, register)
Identity Operator
Test if the two operands share an identity. E.g. is. Is not
Membership Operator
Test whether a value is a member of a sequence e.g. in, not in
Expression
An expression is a combination of values, variables, and operators.

Order of operations

When more than one operator appears in an expression, the order of evaluation depends
on the rules of precedence. For mathematical operators, Python follows mathematical
convention. The acronym PEMDAS is a useful way to remember the rules:

• Parentheses have the highest precedence and can be used to force an expression to
evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 *
(3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression
easier to read, as in (minute * 100) / 60, even if it doesn’t change the result.

• Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is 3,
not 27.

• Multiplication and Division have the same precedence, which is higher than Addition
and Subtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and 6+4/2 is
8, not 5.

• Operators with the same precedence are evaluated from left to right (except
exponentiation). So in the expression degrees / 2 * pi, the division happens first and the
result is multiplied by pi. To divide by 2π, you can use parentheses or write degrees / 2 /
pi. I don’t work very hard to remember rules of precedence for other operators. If I can’t
tell by looking at the expression, I use parentheses to make it obvious.

Data type
a. Immutable
b. Mutable
a. Immutable: strings, numbers and tuples
b. Mutable: Lists, Dictionaries and sets

String
A string is a sequence A string is a sequence of characters. You can access the characters
one at a time with the bracket operator:
fruit = 'banana'
letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to letter. The
expression in brackets is called an index.
The index indicates which character in the sequence you want.
len
len is a built-in function that returns the number of characters in a string
To print last letter in fruit
you can use negative indices, which count backward from the end of the string.
The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on.
Traversal with a for loop
A lot of computations involve processing a string one character at a time. Often they start
at the beginning, select each character in turn, do something to it, and continue until the
end. This pattern of processing is called a traversal. One way to write a traversal is with a
while loop:
fruit = ‘banana’
index = 0
while index < len(fruit):
letter = fruit[index]
print letter
index = index + 1
This loop traverses the string and displays each letter on a line by itself. The loop
condition is index < len(fruit), so when index is equal to the length of the string, the
condition is false, and the body of the loop is not executed. The last character accessed is
the one with the index len(fruit)-1, which is the last character in the string.
Another way to write a traversal is with a for loop:
Fruit = ‘banana’
for char in fruit:
print (char)
String slices
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
s = 'Monty Python'
print s[0:5]
Output
Monty
The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth”
character, including the first but excluding the last. This behavior is counterintuitive, but it
might help to imagine the indices pointing between the characters.
If you omit the first index (before the colon), the slice starts at the beginning of the string. If
you omit the second index, the slice goes to the end of the string:
fruit = 'banana'
fruit[:3]
Output
'ban'
fruit[3:]
Output
'ana'
Strings are immutable It is tempting to use the [] operator on the left side of an assignment,
with the intention of changing a character in a string.
find()
Return the position of the string
Str = ‘Attachment’
[Link](‘me’)
replace()
replace(): Replaces one character/string with another
str = ‘organization'
[Link](‘ation’, ‘e’)
split()
create a split on the basis of character
address = “oyo, ibadan”
[Link](“,”)
count()
return the count of character in the string
str = ‘intelligent’
[Link](‘l’)
upper()
str4 = “banana”
[Link]()
Tuples
A tuple is a sequence of values. The values can be any type, and they are indexed by
integers, so in that respect tuples are a lot like lists. The important difference is that tuples are
immutable. Syntactically, a tuple is a comma-separated list of values: t = 'a', 'b', 'c', 'd', 'e'
Although it is not necessary, it is common to enclose tuples in parentheses: t = ('a', 'b', 'c', 'd',
'e') To create a tuple with a single element, you have to include a final comma:
t1 = 'a',
type(t1).
A value in parentheses is not a tuple:
t2 = ('a')
type(t2) Another way to create a tuple is the built-in function tuple. With no argument, it
creates an empty tuple:
t = tuple()
print t ()
If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of
the sequence:
t = tuple('lupins')
print (t)
Output
('l', 'u', 'p', 'i', 'n', 's')
Because tuple is the name of a built-in function, you should avoid using it as a variable
name.
t = ('a', 'b', 'c', 'd', 'e')
print t[0]
Output
'a'
And the slice operator selects a range of elements.
print t[1:3]
Output
('b', 'c')
Tuple assignment
It is often useful to swap the values of two variables. With conventional assignments, you
have to use a temporary variable. For example, to swap a and b:
temp = a
a=b
b = temp
This solution is cumbersome; tuple assignment is more elegant:
a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions. Each value is
assigned to its respective variable. All the expressions on the right side are evaluated before
any of the assignments. The number of variables on the left and the number of values on the
right have to be the same:
a, b = 1, 2, 3
Output
ValueError: too many values to unpack
More generally, the right side can be any kind of sequence (string, list or tuple). For example,
to split an email address into a user name and a domain, you could write:
addr = 'monty@[Link]'
uname, domain = [Link]('@')
print uname
print domain
Output
monty
[Link]
List
A list is a sequence Like a string, a list is a sequence of values.
In a string, the values are characters; in a list, they can be any type. The values in a list are
called elements or sometimes items. There are several ways to create a new list; the simplest
is to enclose the elements in square brackets ([ and ]):
[10, 20, 30, 40]
['crunchy frog', 'ram bladder', 'lark vomit']
The first example is a list of four integers. The second is a list of three strings. The elements
of a list don’t have to be the same type. The following list contains a string, a float, an
integer, and (lo!) another list: ['spam', 2.0, 5, [10, 20]]
A list within another list is nested.
A list that contains no elements is called an empty list; you can create one with empty
brackets, [].
As you might expect, you can assign list values to variables:
cheeses = ['Cheddar', 'Edam', 'Gouda']
numbers = [17, 123]
empty = []
print(cheeses, numbers, empty)
Output
['Cheddar', 'Edam', 'Gouda'] [17, 123] []
Lists are mutable The syntax for accessing the elements of a list is the same as for accessing
the characters of a string—the bracket operator. The expression inside the brackets specifies
the index. Remember that the indices start at 0:
print cheeses[0]
Output
Cheddar
Unlike strings, lists are mutable. When the bracket operator appears on the left side of an
assignment, it identifies the element of the list that will be assigned.
numbers = [17, 123]
numbers[1] = 5
print numbers
Output
[17, 5]
The element of numbers, which used to be 123, is now 5. You can think of a list as a
relationship between indices and elements. This relationship is called a mapping; each index
“maps to” one of the elements.
List indices work the same way as string indices:
 Any integer expression can be used as an index.
 If you try to read or write an element that does not exist, you get an IndexError.
 If an index has a negative value, it counts backward from the end of the list.
The in operator also works on lists.
cheeses = ['Cheddar', 'Edam', 'Gouda']
'Edam' in cheeses
Output
True
'Brie' in cheeses
Output
False
Traversing a list
The most common way to traverse the elements of a list is with a for loop.
The syntax is the same as for strings:
for cheese in cheeses:
print (cheese)
This works well if you only need to read the elements of the list. But if you want to write
or update the elements, you need the indices. A common way to do that is to combine the
functions range and len:
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
This loop traverses the list and updates each element. len returns the number of elements
in the list. range returns a list of indices from 0 to n − 1, where n is the length of the list.
Each time through the loop i gets the index of the next element. The assignment statement
in the body uses i to read the old value of the element and to assign the new value.
A for loop over an empty list never executes the body:
Although a list can contain another list, the nested list still counts as a single element. The
length of this list is four: ['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
List operations
The + operator concatenates lists:
a = [1, 2, 3]
b = [4, 5, 6]
c=a+b
print c [1, 2, 3, 4, 5, 6]
Similarly, the * operator repeats a list a given number of times:
[0] * 4 [0, 0, 0, 0]
[1, 2, 3] * 3

Output
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three
times.
List slices
The slice operator also works on lists: Lists >>
t = ['a', 'b', 'c', 'd', 'e', 'f']
t[1:3]
Output
['b', 'c']
t[:4]
Output
['a', 'b', 'c', 'd']
Output
t[3:]
['d', 'e', 'f']
If you omit the first index, the slice starts at the beginning. If you omit the second, the slice
goes to the end. So if you omit both, the slice is a copy of the whole list.
t[:]

['a', 'b', 'c', 'd', 'e', 'f']


Since lists are mutable, it is often useful to make a copy before performing operations that
fold, spindle or mutilate lists. A slice operator on the left side of an assignment can update
multiple elements:
t = ['a', 'b', 'c', 'd', 'e', 'f']
t[1:3] = ['x', 'y']
print( t)
['a', 'x', 'y', 'd', 'e', 'f']

FUNCTION
The Function of Functions
A function is a block of organized, reusable sets of instructions that is used to perform some
related actions.
Types of function
1. User Defined Function
2. Built-in Function
User Defined Function
How to define a function?
def func_name (arg1, arg2, arg3, …..):
statements………
return
[expression]
Example
def add (a, b):
sum = a + b
return sum
Function call
A function is called when you pass values (arguments) to a function so it can perform a
task.
Calling the defined function
In pass by value, a copy of the variable is passed to the function. The original variable does
not change. Function works on a duplicate, not the original data.
By Value (immutable)
Example 1
def modify(x):
x = x + 10
print("Inside function:", x)
num = 5
modify(num)
print("Outside funtion:", num)

output
Inside function: 15
Outside funtion: 5

a = 10
def ChangeIt(b):
print("value of b is", b)
b = 100
print("New value of b is", b)
#calling a function by passing value to it
ChangeIt(a)
Output
value of b is 10
New value of b is 100
By Reference (mutable)
Example 1
def modify(x):
[Link](10)
print("Inside function:", x)
num = [1, 2, 3]
modify(num)
print("Outside function:", num)
output
Inside function: [1, 2, 3, 9]
Outside function: [1, 2, 3, 9]

c = [10, 20, 30]


def myfunc(d):
print(“The value of d is”, d)
d[0] =99
d[1] = 98
print(“New value of d is”, d)
myfunc(c)
output
The value of d is [10, 20, 30]
New value of d is [99, 98, 30]

In pass by reference, the function receives the actual variable, not a copy. Changes inside the
function affect the original variable. Function works directly on the original variable.

Test yourself
1. Following function take two parameters and print the first one. Fill the missing
code:
def my_function(fname, lname):
print(___________________)
2. A function which return the x parameter + 10. Fill in the missing code
3. What is the output of:
fruits = (“apple”, “banana”, “cherry”)
if “mango” in fruits:
print(3+4)
else:
print(2*2)

Built –in Function


abs(): returns the absolute value of a number
all(): returns True if all items in an iterable object are true
any(): Returns True if any item in an iterable is true
asci(): Returns a readable version of an object. Replaces non-ascii characters with escape
character
bin(): returns the binary version of a number
bool(): returns the Boolean value of the specified object
What is Lambda Function?
Anonymous function, i.e a function having no name
lambda arguments : expression
Example
x = lambda a : a + 10
print(x(5))
Lambda Function
r = lambda x, y: x * y
r(12, 3)
Power of Lambda: Anonymous function inside another function
def myfunc(n):
return lambda a : a + n
mysum = myfunc(3)
print(mysum(10))
Activity
Write a lambda function that sums argument a, b, and c and print the result.
Classes and Objects
User-defined types
In mathematical notation, points are often written in parentheses with a comma separating the
coordinates. For example, (0,0) represents the origin, and (x,y) represents the point x units to
the right and y units up from the origin.
There are several ways we might represent points in Python:
• We could store the coordinates separately in two variables, x and y.
• We could store the coordinates as elements in a list or tuple.
• We could create a new type to represent points as objects.
Creating a new type is (a little) more complicated than the other options, but it has
advantages that will be apparent soon. A user-defined type is also called a class. A class
definition looks like this:
class Point(object):
"""Represents a point in 2-D space."""
This header indicates that the new class is a Point, which is a kind of object, which is a built-
in type. The body is a docstring that explains what the class is for. You can define variables
and functions inside a class definition.
Defining a class named Point creates a class object.

Object diagram
print Point Because Point is defined at the top level, its “full name” is __main__.Point. The
class object is like a factory for creating objects. To create a Point, you call Point as if it were
a function.
blank = Point()
print blank
The return value is a reference to a Point object, which we assign to blank. Creating a new
object is called instantiation, and the object is an instance of the class.
blank = Point()
print blank
The return value is a reference to a Point object, which we assign to blank. Creating a new
object is called instantiation, and the object is an instance of the class.
When you print an instance, Python tells you what class it belongs to and where it is stored in
memory (the prefix 0x means that the following number is in hexadecimal)
You can assign values to an instance using dot notation:
blank.x = 3.0
blank.y = 4.0
we are assigning values to named elements of an object. These elements are called attributes.
A state diagram that shows an object and its attributes is called an object diagram in the
above diagram.
What is a Class?
A class is a blueprint, template, or design used to create objects.
It defines:
What data something has (attributes)
What actions it can perform (methods)

What is a Class?
A class is a blueprint, template, or design used to create objects.
Think of it like:
 A car design (class)
 The actual cars produced (objects)
Example:
class car:
pass
This creates an empty class called car.
What is an object?
An object is an instance of a class (a real-world representation of that blueprint)
class Car:
pass
car1 = car()
car2 = car()

car 1 and car2 are created from the car class.


What is attributes?
Attributes describe the properties of an object.
class Car:
def __init__(self, brand, color):
[Link] = brand
[Link] = color
car1 = car(“Toyota”, “red”)
car2 = car(“Honda”, “Blue”)

print([Link])
print([Link])

class Car: defines the class


__init__ is a constructor that (runs automatically when object is created)
self refers to the current object
brand and color are attributes
What is a Method?
A method is a function defined inside a class.
It describes what an object can do.
Example 1
class Car:
def __init__(self, brand):
[Link] = brand
def start(self):
print([Link], "is starting")
car1 = Car("Toyota")
[Link]()
Example 2
class Student:
def __init__(self, name, score):
[Link] = name
[Link] = score
def display(self):
print(“Name:”, [Link])
print(“score:”, [Link])
def is_passed(self):
if [Link] >=50:
print([Link], “passed”)
else:
print([Link], “failed”)
student1 = student(“Deborah”, 75)
student2 = student(“Tola”, 40)

[Link]()
student1.is_passed()

[Link]()
student2.is_passed()

Example 3
class BankAccount:
def __init__(self, owner, balance):
[Link] = owner
[Link] = balance
def deposit(self, amount):
[Link] += amount
print("Deposit successful. New balance:", [Link])

def withdraw(self, amount):


if amount > [Link]:
print("Insufficient funds")
else:
[Link] -= amount
print("Withdrawal successful. Balance:", [Link])
account1 = BankAccount("Faith", 1000)
[Link](500)
[Link](300)
[Link](2000)
Output
Deposit successful. New balance: 1500
Withdrawal successful. Balance: 1200
Insufficient funds

In Python, there are three types of methods:


1. Instance Method
2. Class Method
3. Static Method
1. INSTANCE METHOD
An instance method works with object (instance) data.
Key Feature
Uses self
Can access and modify object attributes
Example
Python
class Student:
def __init__(self, name, score):
[Link] = name
[Link] = score
def display(self):
print([Link], "scored", [Link])
s1 = Student("Pelumi", 80)
[Link]()
Real-Life Analogy
Each student:
Has their own name and score
So method must work on individual object
When to Use
Use instance methods when:
 You need to work with object-specific data
 Each object behaves differently
Example:
 Bank account balance
 Student score
 Product price
2. CLASS METHOD
A class method works with the class itself, not individual objects.
Key Feature
 Uses @classmethod
 First parameter is cls
 Works with class variables
Example
class Student:
school = "UI" # class variable
def __init__(self, name):
[Link] = name
@classmethod
def change_school(cls, new_name):
[Link] = new_name
Student.change_school("Atiba University")
print([Link])
cls refers to the class (Student)
Changes affect all objects
Real-Life Analogy
Think of a school name:
 All students share it
 Changing it affects everyone
Use class methods when:
 You want to modify class-wide data
 You don’t need individual object info
Example:
 Change company name
 Count number of objects
3. STATIC METHOD
A static method is a function inside a class that does not depend on class or object.
Key Feature
 Uses @staticmethod
 No self, no cls
 Independent logic
Example
class Math:
@staticmethod
def add(a, b):
return a + b
print([Link](5, 3))

Does not use object or class


Just grouped inside class for organization
Real-Life Analogy
Calculator:
Adding numbers doesn’t depend on a specific calculator object
Use static methods when:
 Logic is related to the class, but
 Does not need class or object data
Example:
Utility functions
Validation
Calculations
conclusion
Question 1:
“Does this method need object data?” Yes → Instance method
Question 2:
“Does it affect all objects?” Yes → Class method
Question 3:
“Does it depend on neither?” Yes → Static method

You might also like