Python Unit 1
Python Unit 1
Python Command Line mode and Python IDEs; Simple Python Program.
Python Basics: lde ntifiers; Keywords; Statements and Ex pressions; Variables; Operators;
Precedence and Assoc iat ion; Data Ty pes; Inde ntatio n; Comments; Built-in Functions- Console
Input and Console 0 ut put, Ty pe Conversions; Python Libraries; Importing Libraries with
Examples.
Python Control FloW: Ty pes of Control Flow; Control Flow State ments- if, else, elif, while loop,
b reak, cont inue statements, for loop State ment; range () and ex it () functio ns.
BCA-IV 1
UNIT-I
Introduction to Python:
Python is a high-leve 1, interpreted, object-oriented programming language that is
widely used for developing various types of applications including web development,
data scie nce, artificial intelligence, and automatio n.
Features of Python:
2. xpresaiVe: Language
p t 3. lnlerpreted Lan
n
1. Simple and easy-to-learn syntax: Python has a simple and readable sy ntax,
making it easy to learn and use, especially for beginne rs.
2. Interpreted language: Pyt lion is an interpr eted language, which means t hat it
does not requir e compilation befo re execution, making it faste r and e asie r to
de bug.
4. Dynamic typing: Pytho n is dy namically type d, which means that variable types
are determined at runtime, allowing for more flexible and adaptable code.
5. Extensive standard library: Pyt lio n comes wit li a large standar d library that
provide s a wide range of tools and modtiles for various tasks, from handling
regtilar expressions to netw ork pro gramming.
B CA- IV
UNIT-I
7. Large and active community: Python has a large and active community of
deve lopers who co ntribtite to o pen-source projects and provide suppor t to
beginne rs.
1.0. Integration capabilities: Pyt lion ran easily inte grate with other languages and
technologies, including C/C++, Java, and .NET, making it a popular choice for
deve loping applications wit li dive rse ter linology stacks.
Applicafions of Python:
1. Web development: Python is widely used for web develop me nt, with po pular
web framew orks suc li as Django and Flask that allow developers to create
dy namic and scalable we b applications.
2. D ata science: Pytlion is a popular language for data science and macliine
learning, wit li librarie s sticli as N umPy, P andas, and Scikit-learn t liat provide
powerftil tools for data analysis and inacliine learning.
4. Artificial intelligence and robotics: Pytho n is used in artificial inte lligerice and
robotics, wit li libraries such as TensorF low, Keras, and PyTorcli t hat provide
powerftil tools for deep le arning and artificial intelligerice.
5. Desktop applications: Pyt lion can be used to create desktop applications using
tools such as Py Qt, wxPyt hon, and Py GTK.
6. Game development: Pyt hon can be used in game deve lo pme nt, wit li libraries
such as Py game that pro vide too1s for creating 2D games.
7. Automation: Python can be used for automation tasks, with tools such as
Selenium and Beatitiful Soup that pro vide web scraping and automation
c apabilities.
8. Scripting: Pyt lion is widely used for scripting tasks, wit li too1s such as Fabric
and Ansible that pro vide automation capabilities for system administration and
netwo rk manage ment.
B CA- IV 3
UNIT-I
Python Versions:
The curre nt stable version of Python as of my knowledge ctito ff date (Septembe r 202 1)
is Pyt lion 3.1 1.2, which was released on 0 cto ber 4, 2.0.2.1. Some of the major versions of
Pyt lion include:
1. Python 1.x: The first version of Python, which was re le ased in 19.9.1.
2. Python 2.x: The second major version of Pytho n, which was released in 2.0.0.0. It
was wide ly used for many years, but its development was discontinued on
January 1, 2.0.2.0.
3. Python 3.x: The third major ve rsion of Pytho n, which was released in 2.0.0.8. It
introduced many new features and impro vements, but also introduced some
bac kward- inc ompatible changes. Pyt lion 3.x is the current and reromme rided
versio n of Pyt lio n for new develo pme nt.
Each major versio n of Python has multiple minor versions, which include bug fixes, improve
me nts, and new fe attires. For example, Pytho n 3. 7, Python 3.8, Pytho n 3.9, and Python
3.10 are all mino r versions of Python 3.x, with earli version introducing new features and
improvements.
lnstallafion of Python:
To install Pyt lion on your c omptite r, you can fo llow t liese general steps:
1. Go to the official Python website at python.org and downlo ad the latest ve rsion
of Pyt lio n that is compatible wit li yo tir operating system (Windows, Mar, or
L inlix).
L ink : https:/ /www.uvthon.o rz/ downloads /
2. Run the downloaded installation file and fo llow the installation wizard. Make
sure to select the optio us yo u want, such as adding Pytho n to your system path
or installing I liird-party libraries.
You can also use a text editor or integrated development environme nt (IDE) to write
and run Python code. Popular text edito rs and ID Es for Pytho n include Visual Studio
Code, PyCharm, Tlionny, Python ID LE, Atom, and S ublime Text.
B CA- IV 4
UNIT-I
Default IDEs:
Tlionny ( L ink: littus: / /zithub. rom /thoririv /tlio ririv / releases /taz/v4.0.2)
Pyc harm
Vistial Sttidio Code
S tiblime Text
1. 0 pen Tlionny ID E and create a new file by clic king on 'F ile' > 'New' or using the
keyboard shortcut Ctrl+ N (Windows/Linux) or Command +N (Mar).
3. Save the file by clic king on 'File' > 'Save' or using the keyboard slio rtctit Ctrl+S
(Windows/L inux) or Command +S (Mac). Clioo se a filename and lo ratio n on yo
tir c omptiter to save the file.
4. Run the program by clic king on 'Run' > 'R tin curre nt script' or using the
keyboard shortcut F5. This will open a new window calle d 'Slie11' at the botto m of
the IDE and display the out put of the program, which slio uld be 'Hello, world!'.
B CA- IV 5
UNIT-I
1. Ide ntifie rs
2. Keywo rds
3. Statements and Expressions
4. Variables
5. 0 perat ors
6. P recede rice and Association
7. Data Types
8. Iride ntation
9. Comme nts
1. Iden tifiers: Ide ntifie rs in Python are name s given to variables, ftinctio us, classes,
modtiles, and other o bjects in the code. An identifie r is a sequence of letters, digits, and
tmdersco res ( ) t hat be gins wit li a letter or tmderscore.
Keyw ordS: Keywords in Pyt lion are reserved words that have a special meaning,
functionality and pin po se in the language.
They are used to define the syntax and structure of the code and cannot be use d as
variable names or identifie rs. Pyt ho n has 3.5 keyw ords, as of versio n 3.10:
B CA- IV 6
UNIT-I
Statements: a state me nt is a unit of code t hat performs a specific action. A pro gram is
made tip of one or more statements. A statement can be a single line of code or a group
of lines of code t hat pe rform a specific task.
In Python, expressio us are evaluated to produce a value. The value of an expression can
be stored in a variable or used in other expressions or statements.
B CA- IV 7
UNIT-I
Var tables: a variable is a named locatio n in memory that stores a value. The value of a
variable can be change d during the execution of a program. Variables can be used to
store differe nt types of data, including numbe rs, strings, and boolean values.
To create a variable in Pyt lion, yo ti simply clio ose a name for the variable and use the
assign ment o perator (=) to assign a value to it. Here are so me examples:
O perators: 0pe rators in Pytlio n are symbols or special keywords that perfo rm
o perations o n valties or variables. Pytlio n stippo rts a wide range of o pe rators,
including
B CA- IV 8
UNIT-I
Example code:
x = 10
# Arithmetic operators
print(x + y) # outputs 13
print(x - y) # outputs 7
print(x * y) # out puts 30
print(x / y) # outputs 3. 3333333333333335
print(x % y) # outputs 1
print(x ** y) # o ut puts 1000
print(x // y) # o ut puts 3
# Comparison o perators
print(x == y) # outputs False
print(x != y) # o ut puts True
print(x < y) # outputs False
print(x > y) # outputs True
print(x <= y) # outputs False
print(x >= y) # outputs True
# Logical operato rs
a = Tr tie
b = False
print(a and b) # outputs False
print(a or b) # outputs Tr tie
print(not a) # out puts False
# B itwise operators
m = 60 # 60 = 0011 1100
n = 13 # 13 = 0000 110 1
print(in & n) # outputs 12 (12 = 0000 1 100)
print(= I n) # o lit puts 61 (61 = 001 1 1101)
print(in ^ n) # o ut puts 49 (49 = 0011 0001)
print(-m) # outputs -6 1 (-6 1 = 1100 00 11)
print(m << 2) # outputs 2 40 (2 40 = 1111 0000)
print(m >> 2) # outputs 15 (15 = 0000 1111)
# Assignment operators
x+=5
B CA- IV 9
Python Programming
print(x) # outputs 15
print(y) # o tit puts 6
Precedence refers to the order in which o pe rators are evaluated. 0 per ato rs with higher
precede rice are evaluated first, while ope rators wit li lowe r precede rice are evaluated
later.
multiplication (*) Iras a liiglie r precede rice t han addition (+), so in the expression 3 + 4 *
5, the multiplication is performe d first, giving 3 + 2.0, wliir li evaluates to 2.3.
Here's a table of the o perat or prece de rice in Pyt lion, fro m highest to lowest:
Association re fers to the order in which operators with the same precede rice are
evaluated. 0 perato rs can be le ft-associative (evaluated from left to right) or right-
associative (evaluated from right to left).
Data Types: Python has several built-in data types that are used to represent
diffe rent kinds of data.
Numeric
Boolean
Sst
Sequence
Type
3. Boolean : boot
boo1: repre se nts truth values, e itlier True or False.
4. Set: set
set: tinordered collection of unique items, for example {1, 2, 3} or {'apple', 'banana',
'clierry'}.
S. Sequence Type:
list: ordered and mtitable collection of items, for example [1, 2, 3] or ['apple', 'banana',
'cherry'].
tuple: ordere d and immutable collectio n of items, for example ( 1, 2, 3) or ('apple',
'banana', 'cherry').
range: immutable seqtie rice of numbers, for example range(0, 10, 2) re presents the
sequence 0, 2, 4, 6, 8.
String:
str: a string of c liaracters, for example ”Hello, world!” or 'Python is fun'.
B CA- IV 11
UNIT-I
Commen Is: In Pyt lion, romments are used to add explanatory or informative note s to
your code. Comments in Pyt lio n are not execute d by the interpreter, and they are
ignore d when the program runs.
To add a co mment in Python, yo ti can use the # symbol. Everyt liing t hat comes after the
# symbol on a line is co nside red a co mme nt and will be ignored by the interpr ete r. For
example:
single- line co mments start wit li the # sy mbo1 and are used to provide brief explanations
of the code. They are often used to make the code mo re readable and tmde rstandable to
other programmers who may be working on the c ode. Single-line ro mments can appear
on the ir own line or at the end of a line of c ode.
M tilti-line co mme nts in Pyt ho n are also known as docstrings. They are used to provide
mo re detailed explanations of the code and are typically used for docume uting
functio us, rlasse s, and modules. Multi-line comments start and end with three double
quotes (”””) and can span multiple lines.
B CA- IV 12
UNIT-I
Func tions: A function is a block of reusable code that performs a specific task.
F tinrtions help to make yo tir rode more modular, reusable, and easier to read and
maintain.
To define a function in Pyt lion, you use the def ke yw ord followe d by the name of the
functio n, the input paramete rs (if any) , and a colo n (:). The body of the function is t lien
indented, and can contain any valid Pyt lio n code.
hX:
de f add numbers(a, b) :
resii lt = a + b
rettn n re stilt
input(): This function is use d to get input from the user t lirotigli the console.
len(): This function is use d to get the lengt li of a seque rice such as a string, list, or tuple.
int(), float(), and str(): Tliese functions are use d to co nve rt o bjects to inte ge rs,
floating-po int numbers, and strings, respectively.
max() and min(): Tliese functions are use d to get the maximum and minimum values
in a sequence, respective ly.
sum[): This function is used to get the sum of all the elements in a sequence.
BCA-IV 1.3
UNIT-I
Console Output:
To display output to the console in Pyt lio n, you can use the print() function. The syntax
for print() is as follows:
Here, value1, value2, etc. are the values t hat you want to display. You can pass any
number of values to the print() ftinctio n, se parated by commas. The sep argtime nt is
used to specify the se parator between the value s (default is a single space). The end
argume nt is used to specify what to appe nd at the e nd of the o tit put (default is a ne
wline c liaracter).
Examples:
Console Input:
To get input from the console in Pyt lio n, you can use the input() function. The syntax for
input() is as fo llows:
input([prompt])
H ere, pro mpt is an o ptional string that is displayed to the use r before in put is requested.
Whe n the input() function is called, the user will be prompted to e nter a value, and that
value will be returne d by the function.
Example:
B CA- IV 14
UNIT-I
Type Conversions: Conversion of one data type to anot lie r using type conve rsion
functio us. Here are some common type co nversio n functions in Python:
float() : T his function is used to convert a value to a flo ating- point number.
boo1() : This functio n is used to conve rt a value to a boolean (T rue or False) value.
Example:
B CA- IV 15
Python Libraries: Pyt lion libraries are colle ctions of pre -writte n code that provide a
set of functio us and tools t hat yo ti can use in your Python programs. Pytho n has a large
and active community of develo pe rs, which has led to the rreatio n of a vast numbe r of
libraries covering a wide range of applicatio us. He re are some of the mo st po pular
Pyt lion libraries:
NumPy: NiimPy is a library for working with large, multi-dime nsio nal arrays and
matrices, and provides a wide range of mat lie matical functio us to operate on them.
Pandas: Pandas is a library for data analysis and maniptilation, providing tools for
handling tabular data, time serie s, and mo re.
Matplotlib: Matplot lib is a libr ary for c reating static, animated, and interactive
vistializatio us in Pyt lio n, and provides a wide range of customizable plot type s.
N umPy: N timPy is a libr ary use d for ntimerical operations and scientific computing.
You c an import it with the following command:
Example:
import ntimpy as np
# Creating an array
my array = np.array( [1,2,3,4])
print(”Arra U sing ntimpy : ”,rny array)
BCA-IV 1.6
Python Con trot FloW: Python contro 1 flow allows yo ti to contro 1 the orde r of
execution of the code based on certain ro nditions or events. The re are several ways to
implement control flow in Pyt lion:
1. Îf: The if state me nt is use d to cliec k if a condition is true, and exectite a block of
code if the co ndition is true. He re's an example:
x=5
if x > 0:
print(”x is positive”) #out put x is positive
2. if else: The if else statement is used to execute one block of code if a condition is
true, and another block of code if the condition is false. He re's an example:
bX:
x = 10
if x > 5:
print(”x is greate r tlian 5”)
e lse:
print(”x is less t han or equal to 5”)
U sing an e lif ladder can be a more e fficient way of testing multiple conditions than using
separate if statements for each co ndition.
hX:
x = 10
if x > 2.0:
print(”x is great er than 20”)
e lif x > 15:
print(”x is great er than 15 but less than or equal to 2.0 ”)
e lif x > 10:
print(”x is great er than 10 but less t han or eEu al to 15”)
e lse:
BCA-IV 1.7
print(”x is less t han or eqdial to 10”)
I terations/Looping: iterations or loo ps are used to execute a block of code
repeatedly. The re are two main types of loops in Pyt lion: for loops and while loo ps.
4. while loop: A while loop is used to execute a blo ck of code repeatedly as long as a
c ertain condition is true.
Syntax:
while condition:
# code blo ck to be executed
c ount = 0
while roii nt < 10:
print(rotmt)
count += 1
5. ION IOO/: The for loop in Python is use d to iterate over a sequence (such as a list,
tuple, or string) and execute a block of code for e acli item in the sequerice. The basic
syntax of a for loop is as follows:
Syntax:
6. break: the break statement is used to imme diately exit a loop, regardless of whether
the loop's conditio n has been satisfied or not. Wlie n the break statement is
executed inside a loop, the loop is terminate d and the program continues executing the
code after the loop. Syntax:
while condition:
# c ode block
if so me ronditio n:
break
# mo re rode
BCA-IV 1.8
i=0
while i < 10:
print(i)
i + -- 1
if i == 5:
break
Output:
7. confinue statements: the continue statement is used to skip over the current
iteration of a loop and move on to the next iteration. Wlie n the co ntintie statement is
executed inside a loop, the code in the loo p's body that follows the continue statement is
skipped, and the loo p pro ceeds wit li the next iteration.
while condition:
# c od e blor k
if so me conditio n:
continue
# mo re code
i=0
while i < 10:
i + -- 1
if i % 2 == 0:
continue
print(i)
Output:
Syntax:
range (sto p)
range (start, stop, step)
Example:
for i in range(5) :
print(i)
Output:
19
exit() : The exit() function is use d to immediately te rminate the Pytho n inte rpreter. It
takes an o ptional integer argument that can be used to specify an exit status.
E x:
20