Python Programming.1st Semester
Python Programming.1st Semester
Python Programming.1st Semester
Unit - 1
1.1 The Essence of Computational Problem Solving in Python
'Computational problem solving' is the iterative process of developing
computational solutions to problems. Computational solutions are expressed as
logical sequences of steps (i.e. algorithms), where each step is precisely defined so
that it can be expressed in a form that can be executed by a computer.
In order to solve a problem computationally, two things are needed:
● A representation that captures all the relevant aspects of the problem.
● An algorithm that solves the problem by use of the representation.
What Is an Algorithm?
An algorithm is a set of commands that must be followed for a computer to
perform calculations or other problem-solving operations. According to its formal
definition, an algorithm is a finite set of instructions carried out in a specific order
to perform a particular task.
An algorithm is a finite number of clearly described, unambiguous “doable”
steps that can be systematically followed to produce a desired result for given input
in a finite amount of time.
Algorithms and Computers: A Perfect Match
Input Devices
CPU
Output Devices
Primary Memory
Secondary Memory
Input Devices
Input device enables the user to send data, information, or control signals to a
computer. The Central Processing Unit (CPU) of a computer receives the input and
processes it to produce the output.
Keyboard
The keyboard is a basic input device that is used to enter data into a computer or
any other electronic device by pressing keys. It has different sets of keys for letters,
numbers, characters, and functions. Keyboards are connected to a computer
through USB or a Bluetooth device for wireless communication.
Types of Keys
Mouse
The most common pointing device is the mouse. The mouse is used to move a
little cursor across the screen while clicking and dragging. The cursor will stop
if you let go of the mouse. The computer is dependent on you to move the
mouse; it won’t move by itself. As a result, it’s an input device.
A mouse is an input device that lets you move the mouse on a flat surface to
control the coordinates and movement of the on-screen cursor/pointer.
The left mouse button can be used to select or move items, while the right
mouse button when clicked displays extra menus.
Joystick
A joystick is a pointing device that is used to move the cursor on a computer
screen. A spherical ball is attached to both the bottom and top ends of the stick.
In a socket, the lower spherical ball slides. You can move the joystick in all four
directions.
Track Ball
Track Ball is an accessory for notebooks and laptops, which works on behalf of a
mouse. It has a similar structure to a mouse. Its structure is like a half-inserted
ball and we use fingers for cursor movement. Different shapes are used for this
like balls, buttons, or squares.
Light Pen
A light pen is a type of pointing device that looks like a pen. It can be used to
select a menu item or to draw on the monitor screen. A photocell and an optical
system are enclosed in a tiny tube. When the tip of a light pen is moved across a
monitor screen while the pen button is pushed, the photocell sensor element
identifies the screen location and provides a signal to the CPU.
Web Camera
Because a web camera records a video image of the scene in front of it, a webcam
is an input device. It is either built inside the computer (for example, a laptop) or
attached through a USB connection. A webcam is a computer-connected tiny
digital video camera. It’s also known as a web camera because it can take images
and record video. These cameras come with software that must be installed on the
computer in order to broadcast video in real-time over the Internet. It can shoot
images and HD videos, however, the video quality isn’t as good as other cameras
(In Mobiles or other devices or normal cameras).
Output Devices
Output Devices are the devices that show us the result after giving the input to a
computer system. Output can be of many different forms like image, graphic
audio, video, etc. Some of the output devices are described below.
I. Monitor
Monitors, also known as Visual Display Units (VDUs), are a computer’s primary
output device. It creates images by arranging small dots, known as pixels, in a
rectangular pattern. The amount of pixels determines the image’s sharpness.
The two kinds of viewing screens used for monitors are described below.
Cathode-Ray Tube (CRT) Monitor: Pixels are minuscule visual elements that
make up a CRT display. The higher the image quality or resolution, the smaller
the pixels.
Flat-Panel Display Monitor: In comparison to the CRT, a flat-panel display is a
type of video display with less volume, weight, and power consumption. They
can be hung on the wall or worn on the wrist.
Flat-panel displays are currently used in calculators, video games, monitors,
laptop computers, and graphical displays.
II. Printer
Printers are output devices that allow you to print information on paper. There are
certain types of printers which are described below.
Impact Printers
Character Printers
Line Printers
Non-Impact Printers
Laser Printers
Inkjet Printers
Impact Printer
Characters are printed on the ribbon, which is subsequently crushed against the
paper, in impact printers. The following are the characteristics of impact printers:
Character Printers
Character Printer has the capability to print only one character at a time. It is of
two types.
Line Printers
Line Printers are printers that have the capability to print one line at a time. It is
of two types.
Drum Printer
Chain Printer
Non-Impact Printers
Characters are printed without the need for a ribbon in non-impact printers.
Because these printers print a full page at a time, they’re also known as Page
Printers. The following are the characteristics of non-impact printers:
Faster
They don’t make a lot of noise.
Excellent quality
Supports a variety of typefaces and character sizes
Laser Printers
Laser Printers use laser lights for producing dots which will produce characters
on the page.
Inkjet Printers
Inkjet printers are printers that use spray technology for printing papers. High-
quality papers are produced in an Inkjet printer. They also do color printing.
III. Speakers
Speakers are devices that produce sound after getting a command from a
computer. Nowadays, speakers come with wireless technology also like
Bluetooth speakers.
IV. Projector
Projectors are optical devices that have the work to show visuals on both types of
screens, stationary and moving both. It helps in displaying images on a big
screen. Projectors are generally used in theatres, auditoriums, etc.
V. Plotter
Plotter is a device that helps in making graphics or other images to give a real
view. A graphic card is mandatorily required to use these devices. These are the
pen-like devices that help in generating exact designs on the computer.
VI. Headphones
Headphones are just like a speaker, which is generally used by a single person or
it is a single-person usable device and is not commonly used in large areas. These
are also called headsets having a lower sound frequency.
Binary representation
The term bit stands for binary digit. A byte is a group of bits operated on
as a single unit in a computer system, usually consisting of eight bits.
An operating system is software that has the job of managing the hardware
resources of a given computer and providing a particular user interface.
Components of CPU
● A programming language must be simple, easy to learn and use, have good
readability, and be human recognizable.
● Abstraction is a must-have characteristic for a programming language in
which the ability to define the complex structure and then its degree of
usability comes.
● A portable programming language is always preferred.
● Programming language’s efficiency must be high so that it can be easily
converted into machine code and its execution consumes little space in
memory.
● A programming language should be well structured and documented so that
it is suitable for application development.
● Necessary tools for the development, debugging, testing, maintenance of a
program must be provided by a programming language.
● A programming language should provide a single environment known as
Integrated Development Environment(IDE).
● A programming language must be consistent in terms of syntax and
semantics.
Introduction to Python
Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.
It is used for:
● Web development (server-side),
● Software development,
● Mathematics,
● System scripting.
Features of Python:
1. Simple
Python is a simple and minimalistic language. Reading a good Python program
feelsalmost like reading English language.
2. Easy to learn
Python uses very few keywords. Python has an extraordinarily simple syntax and
simple program structure.
3. Open Source
There is no need to pay for Python software. Python is FLOSS (Free/Library and
Open Source Software). Its source can be read, modified and used in programs as
desired by the programmers.
4. High level language
When you write programs in Python, you never need to bother aboutthe low- level
details such as managing the memory used by your program, etc.
5. Dynamically typed
Python provides IntelliSense. IntelliSense to make writing your code easier and
more error-free. IntelliSense option includes statement completion, which provides
quick access to valid member function or variables, including global, via the
member list. Selecting from the list inserts the member into your code.
6. Portable
Due to its open-source nature, Python has been ported to (i.e. changed to make it
work on) many platforms. All your Python programs can work on any of these
platforms without requiring any changes at all if you are careful enough to avoid
any system-dependent features.
7. Platform independent
When a Python program is compiled using a Python compiler, it generates byte
code. Python’s byte code represents a fixed set of instructions that run on all
operating systems and hardware. Using a Python Virtual Machine (PVM), anybody
can run these byte code instructions on any computer system. Hence, Python
programs are not dependent on any specific operating system.
8. Procedure and Object Oriented
Python supports procedure-oriented programming as well as object-oriented
programming. In procedure-oriented languages, the program is built around
procedures or functions which are nothing but reusable pieces of programs. In
object- oriented languages, the program is built around objects which combine data
and functionality.
History of python
● Guido van Rossum is the creator of the Python programming language
released in the early 1990s.
● Its name comes from a 1970s British comedy television show called Monty
Python’s Flying Circus.
● Open sourced from the beginning.
FLAVORS OF PYTHON
A flavor of Python simply refers to the different Python compilers. These flavors
are useful to integrate various programming languages into Python. Let us look at
some of these flavors:
C Python, J Python, PyPy, Ruby Python, Python xy, Anaconda Python,
Stockless Python.
Applications of python
● Web and Internet Development
● GUI
● Software Development
● AI and Machine Learning
● Database access
● Network Programming
● Games and 3D Graphics
Who uses python today?
Installing of python
● Python is well supported and freely available at
https://www.python.org/downloads/
● Latest version : 3.8.5
Python IDLE
● An Integrated Development Environment (IDLE) is a bundled set of
software tools for
● Program development.
● An editor for creating and modifying programs
● A translator for executing programs
● A program debugger provides a means of taking control of the execution of
a program
● to aid in finding program errors
The Python Standard Library is a collection of modules, each providing specific
functionality, beyond what is included in the core part of Python.
Python character set
Letters: Upper case and lower case letters
Digits: 0,1,2,3,4,5,6,7,8,9
Special Symbols: Underscore (_), (,), [,], {,}, +, -, *, &, ^, %, $, #, !, Single
quote(‘),
Double quotes(“), Back slash(\), Colon(:), and Semi Colon (;)
White Spaces: (‘\t\n\x0b\x0c\r’), Space, Tab.
Token
A program in Python contains a sequence of instructions.
Python breaks each statement into a sequence of lexical components known as
tokens.
1.8 Literals in Python
A literal in Python is a syntax that is used to completely express a fixed value of a
specific data type. Literals are constants that are self-explanatory and don’t need to
be computed or evaluated. They are used to provide variable values or to directly
utilize them in expressions.
They can also be defined as raw values or data given in variables or constants.
Types of Literals in Python
String literals
Character literal
Numeric literals
Boolean literals
List literal
Tuple literals
Dictionary literals
1. String Literals
A string is literal and can be created by writing a text(a group of Characters )
surrounded by a single(”), double(“), or triple quotes.
Example:
# in single quote Output:
s = 'geekforgeeks' geekforgeeks
# in double quotes geekforgeeks
t = "geekforgeeks" geek
# multi-line String for
m = '''geek geeks
for
geeks'''
print(s)
print(t)
print(m)
2. Character literal
It is also a type of Python string literal where a single character is surrounded
by single or double quotes.
# character literal in single quote Output:
v = 'n' n
# character literal in double quotes a
w = "a"
print(v)
print(w)
3. Numeric literal
They are immutable and there are three types of numeric literal:
Integer
Both positive and negative numbers including 0. There should not be any
fractional part. In this example, We assigned integer literals (0b10100, 50,
0o320, 0x12b) into different variables.
Float
These are real numbers having both integer and fractional parts. In this
example, 24.8 and 45.0 are floating-point literals because both 24.8 and 45.0 are
floating-point numbers.
Complex
The numerals will be in the form of a + bj, where ‘a’ is the real part and ‘b‘ is
the complex part. Numeric literal [ Complex ]
x = 0b10100 #Binary Literals Output:
y = 100 #Decimal Literal 20 100 141 301
z = 0o215 #Octal Literal 100.5 150.0
u = 0x12d #Hexadecimal Literal (5+3.14j) 3.14 5.0
#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)
4. Boolean literal
There are only two Boolean literals in Python. They are true and false.
5. List Literal
List object in Python is a collection of objects of other data type. List is an
ordered collection of items not necessarily of same type. Individual object in the
collection is accessed by index starting with zero.
L1=[1,"Ravi",75.50, True] Output:
print (L1, type(L1)) [1, 'Ravi', 75.5, True] <class 'list'>
6. Tuple Literal
Tuple object in Python is a collection of objects of other data type. Tuple is an
ordered collection of items not necessarily of same type.
T1=(1,"Ravi",75.50, True) Output:
print (T1, type(T1)) [1, 'Ravi', 75.5, True] <class tuple>
1.9 Variables
A variable is “a name that is assigned to a value.”
The assignment operator, = , is used to assign values to variables.
An immutable value is a value that cannot be changed.
>>>num=10 O/P : 10
>>> k=num
>>> print(k)
In Python the same variable can be associated with values of different type during
program execution.
var = 12 integer
var = 12.45 float
var = 'Hello' string
+ Addition a + b = 30
- Subtraction a – b = -10
* Multiplication a * b = 200
/ Division b/a=2
% Modulus b%a=0
Example:
a = 21 Output:
b = 10
a: 21 b: 10 a+b: 31
c=0
c=a+b a: 21 b: 10 a-b: 11
print ("a: {} b: {} a+b: {}".format(a,b,c))
a: 21 b: 10 a*b: 210
c=a-b a: 21 b: 10 a/b: 2.1
print ("a: {} b: {} a-b: {}".format(a,b,c) )
a: 21 b: 10 a%b: 1
c=a*b
print ("a: {} b: {} a*b: {}".format(a,b,c)) a: 2 b: 3 a**b: 8
c=a/b
a: 10 b: 5 a//b: 2
print ("a: {} b: {} a/b: {}".format(a,b,c))
c=a%b
print ("a: {} b: {} a%b: {}".format(a,b,c))
a=2
b=3
c = a**b
print ("a: {} b: {} a**b: {}".format(a,b,c))
a = 10
b=5
c = a//b
print ("a: {} b: {} a//b: {}".format(a,b,c))
The following table contains all comparison operators with their symbols, names,
and examples (assume that the values of a and b are 10 and 20, respectively) –
Example:
a = 21 Output:
b = 10 Line 1 - a is not equal to b
if ( a == b ): Line 2 - a is not equal to b
print ("Line 1 - a is equal to b") Line 3 - a is not less than b
else: Line 4 - a is greater than b
print ("Line 1 - a is not equal to b") Line 5 - a is either less
than or equal to b
if ( a != b ): Line 6 - b is either greater
print ("Line 2 - a is not equal to b") than or equal to b
else:
print ("Line 2 - a is equal to b")
if ( a < b ):
print ("Line 3 - a is less than b" )
else:
print ("Line 3 - a is not less than b")
if ( a > b ):
print ("Line 4 - a is greater than b")
else:
print ("Line 4 - a is not greater than b")
if ( b >= a ):
print ("Line 6 - b is either greater than or equal to b")
else:
print ("Line 6 - b is neither greater than nor equal to
b")
The following table contains all assignment operators with their symbols, names,
and examples –
Operator Example Same As
= a = 10 a = 10
+= a += 30 a = a + 30
-= a -= 15 a = a - 15
*= a *= 10 a = a * 10
/= a /= 5 a=a/5
%= a %= 5 a=a%5
**= a **= 4 a = a ** 4
//= a //= 5 a = a // 5
|= a |= 5 a=a|5
^= a ^= 5 a=a^5
c /= a
print ("a: {} c /= a : {}".format(a,c))
c =2
print ("a: {} b: {} c : {}".format(a,b,c))
c %= a
print ("a: {} c %= a: {}".format(a,c))
c **= a
print ("a: {} c **= a: {}".format(a,c))
c //= a
print ("a: {} c //= a: {}".format(a,c))
The following table contains all bitwise operators with their symbols, names, and
examples –
^ XOR a^b
~ NOT ~a
Example:
a = 20 Output:
b = 10 a= 20 : 0b10100 b= 10 :
print ('a=',a,':',bin(a),'b=',b,':',bin(b)) 0b1010
c=0 result of AND is 0 : 0b0
c = a & b; result of OR is 30 :
print ("result of AND is ", c,':',bin(c)) 0b11110
c = a | b; result of EXOR is 30 :
print ("result of OR is ", c,':',bin(c)) 0b11110
c = a ^ b; result of COMPLEMENT is
print ("result of EXOR is ", c,':',bin(c)) -21 : -0b10101
c = ~a; result of LEFT SHIFT is 80
print ("result of COMPLEMENT is ", c,':',bin(c)) : 0b1010000
c = a << 2; result of RIGHT SHIFT is
print ("result of LEFT SHIFT is ", c,':',bin(c)) 5 : 0b101
c = a >> 2;
print ("result of RIGHT SHIFT is ", c,':',bin(c))
v. Logical Operators
Python logical operators are used to combile two or more conditions and check the
final result. There are following logical operators supported by Python language.
Assume variable a holds 10 and variable b holds 20 then
The following table contains all logical operators with their symbols, names, and
examples –
or OR a or b
Returns True if both variables are the same object and false
is a is b
otherwise.
Returns True if both variables are not the same object and
is not a is not b
false otherwise.
Example:
a = [1, 2, 3, 4, 5] Output:
b = [1, 2, 3, 4, 5] True
c=a False
print(a is c) False
print(a is b) True
print(a is not c)
print(a is not b)
6
*, @, /, //, %
Multiplication, matrix multiplication, division, floor division, remainder
7 +, - Addition and subtraction
8 <<, >> Left Shifts, Right Shifts
9 & Bitwise AND
10 ^ Bitwise XOR
11 | Bitwise OR
12
in, not in, is, is not, <, <=, >, >=, !=, ==
Comparisons, including membership tests and identity tests
13 not x Boolean NOT
14 and Boolean AND
15 or Boolean OR
16 if – else Conditional expression
17 lambda Lambda expression
18 := Walrus operator