PYTHON PROGRAMMING THEORY
UNIT-I
Computer Hardware – Software – Introduction about Python - Characteristics of Python -
Python's features - Literals - Variables and Identifiers - Operators - Data types.
UNIT-II
Boolean Expressions - Selection Control – if, if-else, if-elif- else- Iterative Control - While
Statement, do while and for loop - break, continue, pass. Strings: string slices,
immutability, string functions and methods, string module;
UNIT-III
Program Routines- Defining Functions- Calling Value-Returning Functions- Calling Non-
ValueReturning Functions- Parameter Passing - Keyword Arguments in Python - Default
Arguments in PythonVariable Scope. Recursion: Recursive Functions
UNIT-IV
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists,
list parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations
and methods; advanced list processing – list comprehension
UNIT-V
Files and exception: text files, reading and writing files, format operator; command line
arguments, errors and exceptions, handling exceptions, modules, packages;
TEXT BOOK:
1. Allen B. Downey, “Think Python: How to Think like a Computer Scientist”, 2nd
Edition,
O’Reilly Publishers, 2016
2. Karl Beecher, “Computational Thinking: A Beginner's Guide to Problem Solving and
Programming”, 1st Edition, BCS Learning & Development Limited, 2017
3. Charles Dierbach, “Introduction to Computer Science using Python – A computational
Problemsolving Focus”, Wiley India Edition, 2015.
UNIT-I
Computer Hardware – Software – Introduction about Python - Characteristics of Python -
Python's features - Literals - Variables and Identifiers - Operators - Data types.
SCRIPT MODE(save as file) , INTERACTIVE MODE
Computer hardware includes the physical parts of a computer, such as a case, central
processing unit (CPU), random access memory (RAM), monitor, and mouse which
processes the input according to the set of instructions provided to it by the user and gives
the desired output
Software is a set of programs, which is designed to perform a well-defined function. A
program is a sequence of instructions written to solve a particular problem.
There are two types of software −
System Software
Application Software
System Software
The system software is a collection of programs designed to operate, control, and extend
the processing capabilities of the computer itself. System software is generally prepared by
the computer manufacturers. These software products comprise of programs written in
low-level languages, which interact with the hardware at a very basic level. System
software serves as the interface between the hardware and the end users.
Some examples of system software are Operating System, Compilers, Interpreter,
Assemblers, etc.
Application Software
Application software products are designed to satisfy a particular need of a particular
environment. All software applications prepared in the computer lab can come under the
category of Application software.
Application software may consist of a single program, such as Microsoft's notepad for
writing and editing a simple text. It may also consist of a collection of programs, often
called a software package, which work together to accomplish a task, such as a spreadsheet
package.
Examples of Application software are the following −
Payroll Software
Student Record Software
Inventory Management Software
Income Tax Software
Railways Reservation Software
Microsoft Office Suite Software
Microsoft Word
Microsoft Excel
Microsoft PowerPoint
Characteristics of Python
1. For learning it is easy and to use: Python is easy to learn and use, even for
beginners. The syntax is plain and straightforward, almost like writing in English.
2. Object-oriented: Python is an object-oriented programming language that has
highlights such as code reusability and measured quality. It supports highlights
such as abstraction, encapsulation, inheritance and polymorphism.
3. Interpreted: Python is an interpreted language, which implies line by line the code
is executed. This makes the process faster and more efficient as it eliminates the
need for a compilation step, and if some error occurs, it will not wait for the whole
code to compile. It will throw an error at that particular line itself.
4. Cross-platform: Python has the capability to run on multiple platforms, including
Windows, Mac, Linux, and Unix. This makes it highly portable, allowing
developers to write code on one platform and run it on another.
5. Extensive standard library: Python has an extensive standard library that
contains modules for many everyday tasks, e.g. file input/output, regular
expressions and networks. This reduces the code developers have to write and
saves time and effort.
6. Dynamically typed: Python is dynamically typed, meaning variable types are
determined at runtime. We don't have to tell the data type of the variable explicitly.
This makes the language more flexible and adaptable to changing requirements.
7. High-level language: Python may be a high-level language, meaning that it
abstracts absent numerous of the low-level points of interest of computer hardware.
This permits designers to focus on the problem they are attempting to unravel,
instead of the usage points of interest.
8. Support for numerous programming ideal models: Python supports numerous
programming standards, counting procedural, functional and object-oriented
programming. This makes it exceedingly versatile to distinctive coding styles and
extend necessities.
9. Free and open source: The Python programming language is free and open
source, which suggests it can be utilized on any working framework for
complimentary. You'll be able download Python and the related libraries and
documentation from the official Python site.
10. Extensive feature: The Python programming language can be extended and is
more versatile than many other programming languages. Its adaptability to various
functionalities makes Python a universal programming language in the software
development industry. Code written in different programming languages can be
executed. Python gains new capabilities and functionality by integrating code from
other programming languages.
11. Database support: Python provides robust support for working with databases
through its standard library and third-party packages such as SQLite3, MySQL
Connector, PostgreSQL, SQLAlchemy, and MongoDB. Python also supports
Object-Relational Mapping (ORM) frameworks such as Django ORM and
SQLAlchemy, which provide an abstraction layer on top of databases, making it
easier to work with data in object-oriented Python code.
12. GUI Programming Support: Python provides several GUI programming
frameworks and libraries, including Tkinter, PyQt, and wxPython where. Tkinter is
a standard GUI toolkit included in Python. PyQt delivers a powerful and flexible
toolkit for creating cross-platform desktop GUI applications, and wxPython
provides a native look and feels for desktop GUI applications on Windows,
macOS, and Linux.
13. Python's simplicity, versatility, and readability make it popular for developers
across many industries and applications
Applications of Python
1. Web development: Django, Flask, and Pyramid are popular web frameworks in
Python, used for building applications ranging from small websites to large
enterprise applications.
2. Data science and analytics: Python is a highly demanded language in data science
and machine learning, with popular libraries like NumPy, Pandas, Matplotlib, and
Scikit-learn for data analysis, visualization, and ML.
3. Scientific computing: Python is widely used in scientific computing, with modules
for numerical calculations, optimization, linear algebra, interpolation, and special
functions. Libraries like SciPy and NumPy provide a powerful way to perform
scientific computations.
4. Automation and scripting: Python is extensively used for automation tasks, such
as scripting, testing, and deployment, providing an efficient way to automate
repetitive tasks and integrate systems and services.
5. Desktop GUI applications: Python provides several GUI toolkits like Tkinter,
PyQt, and wxPython, allowing developers to create desktop applications with a
native look and feel.
6. Game development: Python can be used to develop games with libraries like
Pygame, which provides graphics, sound, and input handling tools for game
development.
7. Networking: Python has robust networking libraries, such as sockets and
Requests, which make it easy to create network-based applications, such as web
scrapers and web crawlers.
8. Education: Python's simplicity and ease of use make it a popular choice for
introductory programming courses in academia and online.
9. DevOps: Python is used extensively in the DevOps community for tasks such as
automation, infrastructure management, and deployment. Tools such as Ansible
and SaltStack are written in Python.
10. Finance: Python is widely used for quantitative analysis, algorithmic trading, and
risk management. Banks such as JPMorgan and Goldman Sachs use Python for
financial modeling and analysis.
11. Healthcare: Python is used for medical imaging, data analysis, and research. The
National Institutes of Health (NIH) uses Python for genomic data analysis.
Literals:
Python Literals
Python Literals can be defined as data that is given in a variable or constant.
Python supports the following literals:
1. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single
as well as double quotes to create a string.
Ex: "Aman" , '12345'
Types of Strings:
There are two types of Strings supported in Python:
a) Single-line String- Strings that are terminated within a single-line are known as
Single line Strings.
Example:
text1='hello'
b) Multi-line String - A piece of text that is written in multiple lines is known as
multiple lines string.
There are two ways to create multiline strings:
1) Adding black slash at the end of each line.
Example:
text1='hello\
user'
print(text1)
'hellouser'
2) Using triple quotation marks:-
Example:
str2='''''welcome
to
SSSIT'''
print str2
Output:
welcome
to
SSSIT
Numeric literals:
Numeric Literals are immutable. Numeric literals can belong to following four
different numerical types.
Int(signed Long(long float(floating Complex(complex)
integers) integers) point)
Numbers( can Integers of Real numbers In the form of a+bj where
be both positive unlimited size with both integer a forms the real part and b
and negative) followed by and fractional forms the imaginary part
with no lowercase or part eg: -26.2 of the complex number.
fractional uppercase L eg: eg: 3.14j
part.eg: 100 87032845L
Example - Numeric Literals
x = 0b10100 #Binary Literals
y = 100 #Decimal Literal
z = 0o215 #Octal Literal
u = 0x12d #Hexadecimal Literal
#Float Literal
float_1 = 100.5
float_2 = 1.5e2
#Complex Literal
a = 5+3.14j
print(x, y, z, u)
print(float_1, float_2)
print(a, a.imag, a.real)
Output:
20 100 141 301
100.5 150.0
(5+3.14j) 3.14 5.0
Boolean literals:
A Boolean literal can have any of the two values: True or False.
Example - Boolean Literals
x = (1 == True)
y = (2 == False)
z = (3 == True)
a = True + 10
b = False + 10
print("x is", x)
print("y is", y)
print("z is", z)
print("a:", a)
print("b:", b)
Output:
x is True
y is False
z is False
a: 11
b: 10
Special literals.
Python contains one special literal i.e., None.
None is used to specify to that field that is not created. It is also used for the end of lists
in Python.
Example - Special Literals
val1=10
val2=None
print(val1)
print(val2)
Output:
10
None
Literal Collections.
Python provides the four types of literal collection such as List literals, Tuple literals,
Dict literals, and Set literals.
List:
o List contains items of different data types. Lists are mutable i.e.,
modifiable.
o The values stored in List are separated by comma(,) and enclosed
within square brackets([]). We can store different types of data in
a List.
Example - List literals
list=['John',678,20.4,'Peter']
list1=[456,'Andrew']
print(list)
print(list + list1)
Output:
['John', 678, 20.4, 'Peter']
['John', 678, 20.4, 'Peter', 456, 'Andrew']
Dictionary:
o Python dictionary stores the data in the key-value pair.
o It is enclosed by curly-braces {} and each pair is separated by the
commas(,).
Example
dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}
print(dict)
Output:
{'name': 'Pater', 'Age': 18, 'Roll_nu': 101}
Tuple:
o Python tuple is a collection of different data-type. It is immutable
which means it cannot be modified after creation.
o It is enclosed by the parentheses () and each element is
separated by the comma(,).
Example
tup = (10,20,"Dev",[2,3,4])
print(tup)
Output:
(10, 20, 'Dev', [2, 3, 4])
Example: - Set Literals
set = {'apple','grapes','guava','papaya'}
print(set)
Output:
{'guava', 'apple', 'papaya', 'grapes'}
Variables and Identifiers
A variable is the name given to a memory location. A value-holding Python variable is
also known as an identifier.
Since Python is an infer language that is smart enough to determine the type of a variable,
we do not need to specify its type in Python.
Variable names must begin with a letter or an underscore, but they can be a group of both
letters and digits.
The name of the variable should be written in lowercase. Both Rahul and rahul are distinct
variables.
Identifier Naming
Identifiers are things like variables. An Identifier is utilized to recognize the literals
utilized in the program. The standards to name an identifier are given underneath.
o The variable's first character must be an underscore or alphabet
(_).
o Every one of the characters with the exception of the main person
might be a letter set of lower-case(a-z), capitalized (A-Z),
highlight, or digit (0-9).
o White space and special characters (!, @, #, %, etc.) are not
allowed in the identifier name. ^, &, *).
o Identifier name should not be like any watchword characterized in
the language.
o Names of identifiers are case-sensitive; for instance, my name,
and MyName isn't something very similar.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.
Declaring Variable and Assigning Values
Python doesn't tie us to pronounce a variable prior to involving it in the application. It
permits us to make a variable at the necessary time.
In Python, we don't have to explicitly declare variables. The variable is declared
automatically whenever a value is added to it.
The equal (=) operator is utilized to assign worth to a variable.
Python Variable Types
There are two types of variables in Python - Local variable and Global
variable. Let's understand the following variables.
Local Variable
The variables that are declared within the function and have scope
within the function are known as local variables.
Ex:
# Declaring a function
def add():
# Defining local variables. They has scope only within a function
a = 20
b = 30
c=a+b
print("The sum is:", c)
# Calling a function
add()
Output:
The sum is: 50
We get the error that follows if we attempt to use them outside of the function.
add()
# Accessing local variable outside the function
print(a)
Output:
The sum is: 50
print(a)
NameError: name 'a' is not defined
Global Variables
Global variables can be utilized all through the program, and its
extension is in the whole program. Global variables can be used inside
or outside the function.
By default, a variable declared outside of the function serves as the
global variable.
Ex:
# Declare a variable and initialize it
x = 101
# Global variable in function
def mainFunction():
# printing a global variable
global x
print(x)
# modifying a global variable
x = 'Welcome To Javatpoint'
print(x)
mainFunction()
print(x)
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation:
In the above code, we declare a global variable x and give out a value
to it. We then created a function and used the global keyword to access
the declared variable within the function. We can now alter its value.
After that, we gave the variable x a new string value and then called the
function and printed x, which displayed the new value.
Python Operators
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic Operators
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 10, b = 10
=> a+b = 20
- It is used to subtract the second operand from the first
(Subtraction) operand. If the first operand is less than the second operand,
the value results negative. For example, if a = 20, b = 5 =>
a - b = 15
/ (divide) It returns the quotient after dividing the first operand by the
second operand. For example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For
(Multiplicatio example, if a = 20, b = 4 => a * b = 80
n)
% (reminder) It returns the reminder after dividing the first operand by the
second operand. For example, if a = 20, b = 10 => a%b = 0
** (Exponent) As it calculates the first operand's power to the second
operand, it is an exponent operator.
// (Floor It provides the quotient's floor value, which is obtained by
division) dividing the two operands.
Comparison operator
==,!=,<=,>=,>,<
Assignment Operators
=,+=,-=,*=,%=
** a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign
= 4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign
4//3 = 1 to a.
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise
operators. The examples of Bitwise operators are bitwise OR (|), bitwise
AND (&), bitwise XOR (^), negation (~), Left shift (<<), and Right shift
(>>).
example,
if a = 7
b=6
then, binary (a) = 0111
binary (b) = 0110
hence, a & b = 0011
a | b = 0111
a ^ b = 0100
~ a = 1000
Let, Binary of x = 0101
Binary of y = 1000
Bitwise OR = 1101
8421
1 1 0 1 = 8 + 4 + 1 = 13
Bitwise AND = 0000
0000 = 0
Bitwise XOR = 1101
8421
1 1 0 1 = 8 + 4 + 1 = 13
Negation of x = ~x = (-x) - 1 = (-5) - 1 = -6
~x = -6
Operator Description
& (binary A 1 is copied to the result if both bits in two operands at the
and) same location are 1. If not, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise,
the resulting bit will be 1.
^ (binary If the two bits are different, the outcome bit will be 1, else it will
xor) be 0.
~ The operand's bits are calculated as their negations, so if one
(negation) bit is 0, the next bit will be 1, and vice versa.
<< (left The number of bits in the right operand is multiplied by the
shift) leftward shift of the value of the left operand.
>> (right The left operand is moved right by the number of bits present
shift) in the right operand.
Logical Operators
And,or,not
Operator Precedence
Operator Description
** Overall other operators employed in the
expression, the exponent operator is given
precedence.
~+- the minus, unary plus, and negation.
* / % // the division of the floor, the modules, the division,
and the multiplication.
+- Binary plus, and minus
>> << Left shift. and right shift
& Binary and.
^| Binary xor, and or
<= < > >= Comparison operators (less than, less than equal
to, greater than, greater then equal to).
<> == != Equality operators.
= %= /= //= -= Assignment operators
+=
*= **=
Data Types
The following is a list of the Python-defined data types.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary