Professional Documents
Culture Documents
Basic Python Programming Unit 1
Basic Python Programming Unit 1
Unit - i
Introduction to object oriented programming (oop):
Irrespective of the language that a programmer uses a program written using any
programming language has to be converted into machine language so that the computer can
understand it there are two ways to do this compile the program or interpret the program:
Selecting the perfect language for a particular application at hand is a daunting task.
The selection of language for writing a program depends on the following factors
➢ The type of computer hardware and software on which the program is to be executed
➢ The type of program
➢ The expertise and availability of the programmers
➢ Features to write the application it should have built-in features that support the
development of software that are reliable and less prone to cash lower development
and maintenance
➢ Cost stability and capability to support even more than the expected simultaneous
users
➢ Elasticity of a language that implies the east with which new features or functions can
be added to the existing program
➢ Portability
➢ Better speed of development that include the time it takes to write a code time taken
to find a solution to the problem at hand time taken to find the box available to of
development tools experience and skill of the programmers and testing regime.
Generations of programming languages
High-level programming languages mean that the languages are easily understandable
and close to human language. These languages are similar to human language like English and
machine independent that’s why these languages are called high level programming language.
These languages are easy to understand for people but computers cannot understand
directly. So, it needs to convert the program written in high level language into machine
language using a translator program. These languages are called third generation language.
Some examples of high-level programming languages are Fortran, Basic, Pascal,
Cobol, C, C++, Visual Basic, Java, Oracle, Python etc.
Advantages of High-Level Language:
1. High level languages are programmer friendly. They are easy to learn as well as easy to write
and maintain the program.
2. Less error prone, easy to find bug and debug.
3. The programmer need not to know details of hardware to write a program.
4. It is machine independent language.
5. High level programming results in better programming productivity.
Disadvantages of High-Level Language:
1. The problem with high-level languages is that they cannot communicate directly with the
hardware’s or computers.
2. It needs translator program and It takes additional translation times to translate the source to
machine code.
3. High level programs are comparatively slower than low level programs.
4. Compared to low level programs, they need more memory space to run.
Fourth Generation Language(4GL):
4GL stands for Fourth Generation Language. Fourth Generation Language is also called
very high-level programming language. Fourth generation programming languages are the one
which are closer to human languages rather than the high level or middle level programming
languages. 4GLs are associated with databases and data processing, allowing the efficient
development of business-oriented systems.
Most fourth-generation languages are non-procedural or functional languages that
encourage users and programmers to specify the results they want, while the computer
determines the sequence of instructions that will accomplish those results. Thus, fourth-
generation languages have helped simplify the programming process. Examples of 4GLs
are SQL, Oracle etc.
Fifth Generation Language(5GL):
5GL stands for Fifth Generation Language. Fifth Generation Language is also called
natural language. Fifth generation languages are designed to make the computer solve a given
problem without the programmer. Fifth-generation languages are used mainly in artificial
intelligence research and to manufacture artificial intelligence (AI) based devices or machines.
Intelligent Compiler is used to translate the program written in 5GL to machine language.
Examples of 5GLs PROLOG (PROgramming LOGic), LISP, Mercury etc.
programming paradigms
Each of these paradigms has its own strengths and weaknesses and no single paradigm can
suit all applications.
Monolithic Programming
Procedural Programming
In procedural languages, a program is divided into subroutines that can access global
data. To avoid repetition of code, each subroutine performs a well-defined task. A subroutine
that needs the service provided by another subroutine can call that subroutine.
Advantages:
Disadvantages:
✓ No concept of reusability
✓ Requires more time and effort to write programs
✓ Programs are difficult to maintain
✓ Global data is shared and therefore may get altered (mistakenly)
Structured Programming:
Structured programming was basically defined to be used in large programs that require
large development team to develop different parts of the same program. Structured
programming employs a top-down approach in which the overall program structure is broken
down into separate modules. In structured programming, the program flow follows a simple
sequence Besides sequential flow, structured programming also supports selection and
repetition as mentioned here.
Selection allows for choosing any one of a number of statements to execute, based on
the current status of the program. Selection statements contain keywords such as ‘if’, ‘then’,
‘end if’, or ‘switch’ that help to identify the order as a logical executable.
In repetition, a selected statement remains active until the program reaches a point
where there is a need for some other action to take place. It includes keywords such as ‘repeat’,
‘for’, or ‘do… until’. Essentially, repetition instructs the program as to how long it needs to
continue the function before requesting further instructions.
With the increase in size and complexity of programs, there was a need for a new
programming paradigm that could help to develop maintainable programs. To implement this,
the flaws in previous paradigms had to be corrected. Consequently, OOP was developed.
monolithic, procedural, and structured programming paradigms are task-based as they focus
on the actions the program should accomplish. However, the object-oriented paradigm is task-
based and databased. In this paradigm, all the relevant data and tasks are grouped together in
entities known as objects. The striking features of OOP include the following:
Object Oriented programming brings programming close to real life, as we are always dealing
with an object, performing operations on it, using it's methods and variables etc. OOP is
designed in such a way that one should focus on an object while programming and not the
procedure. It is necessary to understand some of the concepts used extensively in object-
oriented programming. These include:
• Objects • Classes
• methods • Inheritance
• delegation • reusability
Classes
self.salary = salary
self.id = id
Class creates a user-defined data structure, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class.
Objects
An object is a real-life entity. An object is the collection of various data and functions that
operate on those data. An object contains the following properties.
o State - The attributes of an object represent its state. It also reflects the properties of an
object.
o Behaviour - The method of an object represents its behaviour.
o Identity - Each object must be uniquely identified and allow interacting with the other
object.
emp_1=employee('aayushi','johari',350000)
emp_2=employee('test','test',100000)
print(emp_1.email)
print(emp_2.email)
Methods
message passing
A request for an object to perform one of its operations is called a message. Operation
means method/function. A message cannot go automatically it creates an interface, which
means it creates an interface for an object. The interface provides the abstraction over the
message means hide the implementation. So, we get to know, An interface is a set of
operations that a given object can perform. All communication between objects is done via
message is called message passing, as people exchange information similarly the sending
and receiving of information by the object is said to be message passing, to make possible
message passing the following things have to be followed to be done:
Inheritance
1. Code reusability- we do not have to write the same code again and again; we can just
inherit the properties we need in a child class.
2. It represents a real-world relationship between parent class and child class.
3. It is transitive in nature. If a child class inherits properties from a parent class, then all
other sub-classes of the child class will also inherit the properties of the parent class.
Polymorphism
Polymorphism is a concept of object-oriented programming, which means multiple
forms or more than one form. Polymorphism enables using a single interface with input of
different datatypes, different class or may be for different number of inputs.
OOP stands for object-oriented programming. It offers many benefits to both the
developers and the users. Object-orientation contributes to the solution of many problems
associated with the development and quality of software products. The new technology
promises greater programmer productivity, better quality of software and lesser maintenance
cost. The primary advantages are:
Merits:
• Through inheritance, we can eliminate redundant code and extend the use of existing
classes.
• We can build programs from the standard working modules that communicate with one
another, rather than having to start writing the code from scratch. This leads to saving
of development time and higher productivity.
• The principle of data hiding helps the programmer to build secure programs that cannot
be invaded by code in other parts of the program.
• It is possible to map objects in the problem domain to those objects in the program.
• Message passing techniques for communication between objects make the interface
descriptions with external systems much simpler.
Demerits:
Python 1.0 January 1994 • Functional programming tools (lambda, map, filter and reduce).
• Support for complex numbers.
• Functions with keyword arguments
Python 3.6.5 March 2018 • Utilities for automatic conversion of Pytthon 2.x code
Script Mode
In script mode, we type Python program in a file and then use the interpreter to execute the
content from the file.
To create and run a Python script, we will use following steps in IDLE, if the script mode is
not made available by default with IDLE environment.
literal constants
A literal is an explicit representation of a value. Generally, literals are a notation for
representing a fixed value in source code. They can also be defined as raw value or data given
in variables or constants. In python, we have different types of literals such as string literals,
numeric literals, Boolean literals and a special literal.
Numeric literals
Numeric literals are those that are initialized to numeric data type object. All forms of
positive and negative numbers including integer number, real number, complex number,
hexadecimal, binary number and octal number belong to numeric literals.
Integers in python are numbers with no fractional component. An integer representing a
decimal number can be defined as follows.
>>> 10
10
>>> -10
-10
>>> 2455642
2455642
We can also define integers from other number systems. A binary number is represented as a
numeric literal starting with ‘0b’ and consists of digits 0 and 1 as follows.
>>> 0b10110101
181
>>> 0b1010
10
>>> 0b0101
5
A number in the hexadecimal number system starts with ‘0x’ and can be represented in python
as follows.
>>> 0xab
171
>>> 0xa1
161
>>> 0x10
16
An integer literal in the octal number system starts with ‘0o’ and can be represented in python
as follows.
>>> 0o10
8
>>> 0o124
84
A floating point literal in python represents a real number which consists of Integral as well as
fractional part. A floating point number in the decimal number system can be represented as
follows.
>>> 3.45
3.45
>>> 3.e25
3e+25
Complex numbers are in the form of a+bj where ‘a’ represents the real part and ‘b’ represents
the imaginary part of the complex number. A numeric literal representing a complex number
can be written as follows.
>>> 4+5j
(4+5j)
>>> 4.5+8j
(4.5+8j)
PYTHON SYNTAX
Python Indentations
Where in other programming languages the indentation in code is for readability only, in
Python the indentation is very important.
Example
Python will give you an error if you skip the indentation:
Example
Comments
Python has commenting capability for the purpose of in-code documentation. A comment is
text that doesn’t affect the outcome of a code, it is just a piece of text to let someone know what
you have done in a program or what is being done in a block of code.
In Python, a single line comment starts with a hash character (#), and is followed by text that
contains further explanations.
Example
Python doesn't offer a separate way to write multiline comments. However, there are other
ways to get around this issue. We can use # at the beginning of each line of comment on
multiple lines.
Example
Docstrings
Python uses triple quotes at the beginning and end of the docstring:
Example
Keywords are the reserved words in Python. In Python, keywords are case sensitive. There are
33 keywords in Python
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
1. The name of the variable must always start with either a letter or an underscore (_). For
example: _str, str, num, _num are all valid name for the variables.
2. The name of the variable cannot start with a number. For example: 9num is not a valid
variable name.
3. The name of the variable cannot have special characters such as %, $, # etc, they can only
have alphanumeric characters and underscore (A to Z, a to z, 0-9 or _ ).
4. Variable name is case sensitive in Python which means num and NUM are two different
variables in python.
Python provides various standard data types that define the storage method on each of them.
The data types defined in Python are given below.
Getting the Data Type
Python provides the type() function to know the data-type of the variable. Similarly, the
isinstance() function is used to check an object belongs to a particular class
PYTHON VARIABLES
A Python variable is a reserved memory location to store values. In other words, a variable in
a python program gives data to the computer for processing.
Creating Variables
Unlike other programming languages, Python has no command for declaring a variable.A
variable is created the moment you first assign a value to it.
Variables do not need to be declared with any type and can even change type after they have
been set.
Example
v
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for Python variables:
Output Variables
The Python print statement is often used to output variables. To combine both text and a
variable, Python uses the + character:
Example
You can also use the + character to add a variable to another variable:
Example
Example
If you try to combine a string and a number, Python will give you an error:
Example
PYTHON NUMBERS
There are three numeric types in Python:
• int
• float
• complex
Variables of numeric types are created when you assign a value to them:
To verify the type of any object in Python, use the type() function:
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Example
Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Example
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example
Complex
Example
PYTHON STRINGS
String Literals
• String literals in python are surrounded by either single quotation marks, or double
quotation marks.
• 'hello' is the same as "hello".
• Strings can be output to screen using the print function. For example: print("hello").
• Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters. However, Python does not have a character data type,
a single character is simply a string with a length of 1. Square brackets can be used to
access elements of the string.
Example
Get the character at position 1 (remember that the first character has the position 0):
Example
Example
The strip() method removes any whitespace from the beginning or the end:
Example
Example
Example
The split() method splits the string into substrings if it finds instances of the separator:
Programs often need to obtain data from the user, usually by way of input from the keyboard.
The simplest way to accomplish this in Python is with input().
input([<prompt>])
input() pauses program execution to allow the user to type in a line of input from the keyboard.
Once the user presses the Enter key, all characters typed are read and returned as a string:
Note that the newline generated when the user presses the Enter key isn’t included as part of
input() always returns a string. If you want a numeric type, then you need to convert the
string to the appropriate type with the int(), float(), or complex() built-in functions:
Writing Output to the Console
The simplest way to produce output is using the print() function where you can pass zero or
more expressions separated by commas. This function converts the expressions you pass into
a string before writing to the screen.
To squish objects together without any space between them, specify sep='':
The end= Keyword Argument
The keyword argument end=<str> causes output to be terminated by <str> instead of the
default newline:
The process of converting the value of one data type into another type is called Type
Conversion. Python has two types of type conversion.
Example
Example 2
Explicit Type Conversion
Python defines type conversion functions like int(), float(), str() to directly convert one data
type into another. This type of conversion is also called typecasting because the user casts
(change) the data type of the objects.
int(a, base)
float()
This function is used to convert any data type to a floating point number.
ord()
This function is used to convert a character into integer (ascii value of character).
hex()
str()
Example
PYTHON OPERATORS
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Python Assignment Operators
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
Identity operators are used to compare the objects, not if they are equal, but if they are the same
object, with the same memory location: