fundamentals of programming
fundamentals of programming
Object-Oriented
Programming
Unit 1
❖ define terms related to
programming
❖ distinguish procedural
programming and OOP
Objectives
2
The Task of
Programming
3
❖ Programming
− the process of preparing an instructional program for a device
(such as a computer)
• program – set of instructions that helps the computer to perform
tasks
❖ Types of Errors
− Syntax errors
− Logical errors
− Run-time errors
4
Programming
Universals
5
❖ Programming language
− used to write a program or set of instructions
− categorized into three types
• Machine level language
• Assembly level language
• High-level language
6
❖ Machine language
− lowest level of programming language
− handles binary data
− directly interacts with system
− not portable and non-readable to humans
7
❖ Assembly language
− a middle-level language
− consists of a set of instructions in a specific format called
commands
− uses symbols to represent field of instructions
− very close to machine level language
− should have an assembler to translate assembly level program
to machine level program
− in human-readable format and takes lesser time to write a
program and debug it
Assembly Language Machine Code
if age < 18 {
printf("You are not eligible to vote");
} else {
printf("You are eligible to vote");
}
9
❖ Interpreter
− program that translates programming language instructions
one line at a time
❖ Compiler
− translates the entire program at one time
10
❖ Control structures
− logic components in programs
− Sequence structure
• steps execute one after another, without interruption
− Selection structure
• used to perform different tasks based on a condition
− Loop structure
• repeats actions while the condition remains unchanged
11
Procedural
Programming
12
❖ Procedural programs
− consist of a series of steps or procedures that take place one after
the other
− based on the concept of calling procedure
• procedures - or routines, subroutines, or functions, consist of a series
of computational steps to be carried out
− examples:
• COBOL
• BASIC
• ALGOL
• FORTRAN
• Pascal
• C
13
14
Object-Oriented
Programming
15
❖ Object-oriented programming
− based on the concept of objects that interact with the real
world
• objects - contain properties in the form of attributes and
behaviors in the form of methods
− most are class-based, objects are instances of classes
− examples:
• Java
• C++
• C#
• Python
• PHP
• JavaScript
16
Procedural Programming Object-Oriented Programming
The program is divided into small The program is divided into small
parts called functions parts called objects
Adding new data and functions is Adding new data and function is
not easy easy
17
❖ Why is OOP better than procedural programming?
− it provides data security by hiding sensitive data from users
− it can be used to model objects in the real world
− it can be used to create complicated large-scale applications
18
Creating
Comments
19
Comments
− used to explain the code
− used to make the code more readable
− start with a #
20
Multiline Comment
− Python does not have a syntax for this
− to add a multiline comment, use # for each line or use a
multiline string
• String literals that are not assigned to a variable are ignored
21
Basic Program
Elements
22
❖ A Python program consists of one or more modules
− module is just a file of Python code, which can include
statements, function definitions, and class definitions
• a script or a short Python program, can be contained in one
module
23
Lexical Elements
❖ the types of words or symbols used to construct sentences
− some basic symbols are keywords, such as if, while, and
def
− identifiers (names), literals (numbers, strings, and other built-
in data structures), operators, and delimiters (quotation
marks, commas, parentheses, square brackets, and braces)
• among the identifiers are the names of built-in functions
24
Spelling and Naming Conventions
❖ Python keywords and names are case-sensitive
− while is a keyword, While is a programmer-defined name
25
Variables and
Data Types
26
❖ Variables
− named locations in computer memory
− languages define rules for naming variables
− should have meaningful names
27
❖ A variable can have a short name (like x and y) or a more
descriptive name (age, carname, total_volume).
28
❖ Use names that describe their role in a program
− variable names
• nouns or adjectives: denote Boolean values
− function and method names
• verbs: denote actions
• nouns or adjectives: denote values returned
30
Literals
❖ Numbers
− integers or floating-point numbers are written as they are in
other programming languages
❖ The Boolean values True and False are keywords.
❖ Some data structures, such as tuples, lists, and dictionaries,
also have literals
31
Data Typing
− any variable can have a value of any type
− variables are not declared to have a type, they are simply
assigned a value
− all values or objects have types
32
Name Type
Text Type str
Numeric Types int, float, complex
Sequence Types list, tuple, range
Mapping Type dict
Set Types set, frozenset
Boolean Type bool
bytes, bytearray,
Binary Types
memoryview
None Type NoneType
33
Setting the Specific Data Type
x = ["lemon", "strawberry", "orange"] list
x = ("lemon", "strawberry", "orange") tuple
x = range(7) range
x = {"name" : "Johnny", "age" : 30} dict
x = {"lemon", "strawberry", "orange"} set
x = frozenset({"lemon", "strawberry", "orange"}) frozenset
x = True Bool
x = b"Hello" bytes
x = bytearray(6) bytearray
x = memoryview(bytes(6)) memoryview
x = None NoneType
34
Getting the Data Type
❖ Use the type() function
35
The int Data Type
❖ int or integer
− a positive or negative whole number without decimals, of
unlimited length
36
The float Data Type
❖ float or floating-point number
− a positive or negative number
containing one or more decimals
37
The complex data type
❖ Complex numbers
− written with a "j" as the imaginary part
38
Type Casting
39
Type Conversion
44
String Length
❖ Use the len() function
45
Slicing Strings
46
Modify Strings
47
String Concatenation
❖ To concatenate, or combine, two strings you can use the +
operator
48
Format Strings
❖ format()
− to format selected parts of a string
49
50
Formatting Output
51
Ways to Format Output
❖ Use formatted string literals
− begin a string with f or F before the opening quotation mark
or triple quotation mark
❖ The str.format() method of strings can help make the
output look fancier
❖ User can do all the string handling by using string slicing
and concatenation operations to create any layout that the
user wants.
❖ The string type has some methods that perform useful
operations for padding strings to a given column width.
52
Formatting output using String modulo
operator(%)
− interprets the left argument much like a printf()-style format
string to be applied to the right argument
53
Formatting output using format() method
− format() method was added in Python(2.6)
− use {} to mark where a variable will be substituted and can
provide detailed formatting directives, and the information to
be formatted
54
Formatting output using String method
− output is formatted by using string slicing and concatenation
operations
− few methods which helps to formatting an output: str.ljust(),
str.rjust(), and str.center()
55
Padding and Aligning Strings
− by default values are formatted to take up only as many
characters as needed to represent the content
− it is also possible to define that a value should be padded to a
specific length
56
❖ And also center align values:
57
❖ You can decide on the padding character:
58
Truncating Long Strings
❖ Inverse to padding it is also possible to truncate overly
long values to a specific number of characters.
59
Combining truncating and padding
60
Numbers
❖ Integers
❖ Floats
61
Padding Numbers
62
Escape Character
− to insert characters that are illegal in a string, use an escape
character
• backslash \ followed by the character you want to insert.
Code Result
\’ Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value
63
64
Python Booleans
❖ Either True or False
65
❖ bool() function evaluates any value and returns True or
False
66
❖ Most values are True
− any string, except empty strings
− any number, except 0
− any list, tuple, set, and dictionary, except empty ones
67
❖ Values which return False
− bool(False)
− bool(None)
− bool(0)
− bool("")
− bool(())
− bool([])
− bool({})
68
Basic Data
Structures
❖ Data Structures
− way of organizing data so that it can be accessed more
efficiently
− “containers” that organize and group data according to type
70
Basic Python Data Structures
❖ List
− a collection which is ordered, changeable, and allows
duplicate members
❖ Tuple
− a collection which is ordered, unchangeable, and allows
duplicate members
❖ Set
− a collection which is unordered, unchangeable, unindexed
and does not allow duplicate members
• items are unchangeable, but items can be added or removed
❖ Dictionary
− a collection which is ordered, changeable, and does not allow
duplicate members
• as of Python version 3.7, dictionaries are ordered
71
List
− just like the arrays declared in other languages, which is an
ordered collection of data
− very flexible because it can contain different data types
72
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified
value
extend() Add the elements of a list (or any iterable), to the end
of the current list
index() Returns the index of the first element with the specified
value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
73
Tuple
− a collection of Python
objects like a list but are
immutable in nature
74
75
Method Description
count() Returns the number of times a specified value
occurs in a tuple
index() Searches the tuple for a specified value and returns
the position of where it was found
76
Set
− an unordered
collection of data that
is immutable and does
not allow any
duplicate element
− used to include
membership testing
and eliminating
duplicate entries
− can contain different
data types
77
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference
between two or more sets
difference_update() Removes the items in this set that are also
included in another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two
other sets
intersection_update() Removes the items in this set that are not
present in other, specified set(s)
78
Method Description
isdisjoint() Returns whether two sets have a
intersection or not
issubset() Returns whether another set contains
this set or not
issuperset() Returns whether this set contains
another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric
differences of two sets
symmetric_difference_update() inserts the symmetric differences from
this set and another
union() Return a set containing the union of
sets
update() Update the set with the union of this set
and others
79
Dictionary
− an ordered collection of data values
− holds the key:value pair
• key - an object which can never change like strings, numbers,
tuples, etc.
− cannot have two items with the same key
80
81
82
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does
not exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value
pairs
values() Returns a list of all the values in the dictionary
83