0% found this document useful (0 votes)
2 views

fundamentals of programming

This document provides an overview of object-oriented programming (OOP) and contrasts it with procedural programming. It defines key programming concepts, types of programming languages, and basic program elements, while also discussing data types and structures in Python. The document emphasizes the advantages of OOP, such as data security and the ability to model real-world objects.

Uploaded by

kayelpat2708
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

fundamentals of programming

This document provides an overview of object-oriented programming (OOP) and contrasts it with procedural programming. It defines key programming concepts, types of programming languages, and basic program elements, while also discussing data types and structures in Python. The document emphasizes the advantages of OOP, such as data security and the ability to model real-world objects.

Uploaded by

kayelpat2708
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

An Overview of

Object-Oriented
Programming
Unit 1
❖ define terms related to
programming

❖ distinguish procedural
programming and OOP
Objectives

❖ identify basic program elements

❖ recognize different data types

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

❖ Learning a computer programming language requires


learning both its vocabulary and syntax
− syntax – rules of any language

❖ 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

SUB AX, BX 0010101110000011

MOV CX, AX 100010111001000


MOV DX, 0 10111010000000000000000
8
❖ High-level language
− uses format or language that is most familiar to users
− instructions in this language are called codes or scripts
− needs a compiler and interpreter to convert high-level
language program to machine level language
− examples: C++, Python, Java
− easy to write and is less time-consuming
− human-readable language

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

❖ Run a program by issuing a command to execute the


program statements

❖ Test a program by using sample data to determine


whether the program results are correct

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

❖ During program execution, any given procedure can be called


by other procedures or by itself.

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

Has access specifiers like private,


No access specifier
public, protected, etc.

Adding new data and functions is Adding new data and function is
not easy easy

No proper way of hiding data so it Provides data hiding so it is more


is less secure secure
Overloading is not possible Overloading is possible

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

❖ Longer and more complex programs typically include one


main module and one or more supporting modules
− the main module contains the starting point of program
execution
− supporting modules contain function and class definitions

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

❖ A name can begin with a letter or an underscore (_),


followed by any number of letters, underscores, or digits

25
Variables and
Data Types

26
❖ Variables
− named locations in computer memory
− languages define rules for naming variables
− should have meaningful names

❖ In Python, a variable is created when you assign a value to


it. It has no command for declaring a variable.

27
❖ A variable can have a short name (like x and y) or a more
descriptive name (age, carname, total_volume).

❖ Rules for Python variables:


− a variable name must start with a letter or the underscore
character
− a variable name cannot start with a number
− a variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _)
− variable names are case-sensitive (age, Age and AGE are
three different variables)

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

Type of Name Examples

Variable salary, hoursWorked, isAbsent


Constant ABSOLUTE_ZERO, INTEREST_RATE
Function or Method printResults, cubeRoot, input
Class BankAccount, SortedSet
29
Syntactic Elements
− the types of sentences (expressions, statements, definitions,
and other constructs) composed from the lexical elements
• Python uses white space (spaces, tabs, or line breaks) to mark the
syntax of many types of sentences
• indentation and line breaks are significant in Python code

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

− can also be scientific numbers


with an "e" to indicate the power
of 10

37
The complex data type
❖ Complex numbers
− written with a "j" as the imaginary part

38
Type Casting

39
Type Conversion

❖ Note: You cannot convert


complex numbers into
another number type.
Python Casting
❖ Type casting
− or type conversion, convert from one data type to another
❖ Implicit Type Conversion
− type conversion is done automatically, without any user
involvement
❖ Explicit Type Conversion
− using predefined functions that act as
a constructor of another data type
• str()
• int()
• float()
The String Data Type
− ‘Hello World’ or “Hello World”

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

❖ Align right: Align Left

➢ default alignment is left


➢ the highlighted parts are white spaces

56
❖ And also center align values:

❖ When using center alignment where the length of the


string leads to an uneven split of the padding characters
the extra character will be placed on the right side:

➢ the highlighted parts are the


whole string with white spaces
as padding characters

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.

❖ The number behind a . in the format specifies the precision


of the output. For strings that means that the output is
truncated to the specified length.

59
Combining truncating and padding

60
Numbers
❖ Integers

❖ Floats

61
Padding Numbers

❖ For floating points the padding value represents the length


of the complete output.

❖ For integer values

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

You might also like