BCA Python Unit-1
BCA Python Unit-1
( PYTHON PROGRAMMING )
UNIT-I
Syllabus:
Getting Started with Python: Introduction to Python , Python Keywords ,
Identifiers , Variables , Comments, Data Types , Operators, Input and Output , Type
Conversion , Debugging . Flow of Control, Selection , Indentation , Repetition , Break
and Continue Statement , Nested Loops .
Strings- String Operations , Traversing a String , String handling Functions.
Introduction
Python is a very powerful high-level, general-purpose, object-oriented
programming language created by Guido van Rossum in 1989. Python is very
popular for developers and professionals because, it has a rich set of supporting
libraries, and add-on modules. It is a cross-platform(platform-independent) language
and runs on all major operating systems including Windows, Linux, and Macintosh.
Python comes with a powerful and easy to-use graphical user interface (GUI) toolkit
that makes the task of developing GUI applications.
The Python programming language was conceived in the late 1980s, and its
implementation was started in December 1989 by Guido van
Rossum at CWI(Centrum Wiskunde & Informatica) in the Netherlands as a
successor of ABC programming language. Python was published in 1991.
2) Expressive Language
Python can perform complex tasks using a few lines of code.
3) Interpreted Language
Python is an interpreted language, it means the Python program is executed
one line at a time. The interpreted language makes debugging easy and
portable.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux,
UNIX, and Macintosh, etc. So, we can say that Python is a portable language.
6) Object-Oriented Language
Python supports object-oriented language.It supports object-oriented
concepts inheritance, polymorphism, encapsulation, etc.
9) Integrated
Python can be integrated with other languages,
like C, C++, and Java.
In command line mode, you type Python instructions one line at a time.
Keywords
Keywords are the reserved words in Python. There are 35 keywords in Python
3.10 This number can vary in different versions of Python. All the keywords except
True, False and None are in lower case. List of Keywords in Python 3.10 given below.
Note: you can always get the list of keywords in your current version by typing the
following in the prompt.
>>> import keyword
>>>keyword.kwlist
>>>len(keyword.kwlist)
Identifiers
Identifier is a user-defined name given to a variable, function, class, module,
etc. using the combination of following characters.
1. Alphabets : A to Z and a to z
2. Digits : 0 to 9
3. Underscore : _
Variables
Variables are used for storing data in a program. Therefore, by assigning different
data types to variables(you can store numbers, strings, etc.). In Python, we don't
need to specify the data-type of the variable. When we assign some value to the
variable, it automatically allocates the memory to the variable at run time.
For example
A = 10
value = 10.0
st_value="Hello World!"
You can see in the preceding examples the variable can be a single character or a
word or words connected with underscores.
Multiple Assignment
1) Python allows you to assign a single value to several variables.
For example
a=b=c=1
Here, an integer value 1 is assigned all the three variables.
2) Python allows you to assign multiple values to several variables.
For example
a,b,c=1,2,'Hello'
Here, two integer values 1 and 2 are assigned to variables a and b respectively, and
a string "Hello" is assigned to the variable c.
Numeric
Integers
This value is represented by int class. It contains positive or negative
whole numbers (without fractions or decimals). Integer datatype has
no limit In Python.
Eg:
n=10
a=b=c=1
x,y=100,200
Float
This value is represented by the float class. It is a real number with a
floating-point representation. It is specified by a decimal point.
Eg:
n=10.25
Complex Number:
A complex number is represented by a complex class. It is specified
as (real part) + (imaginary part)j . For example – 2+3j, where 3j is the
imaginary component and is equal to √-9 (√9 × √−1 = 3i or 3j).
Eg1:
>>> complex(2,3)
(2+3j)
Sequence Type
Strings:
Sequences of Unicode characters. A string can be defined either Single
quotes (or) double quotesor (or) triple quotes. By using triple quotes we can
write multi-line strings.
S1=’abcd’
S2=”welcome”
S3=’’’ Welcome to Python
Programming ’’’
List
List is are just like array that is mutable (changeable) sequence of elements. Each
element or value that is inside a list is called an item. A list is created by placing all
the items (elements) inside a square brackets, separated by comma. It can have any
number of items and they may be of different types (integer, float, string etc.).
Syntax:
List_Name = [item-1,item-2,………,item-n]
# empty list
a=[]
# list of integers
a = [1, 2, 3]
Tuples
A tuple is a sequence of immutable(Unchanged) elements. Tuples are just like
lists. The differences between tuples and lists are, the tuples cannot be changed
unlike lists and tuples use parentheses, whereas lists use square brackets.
Note: parentheses brackets are optional for Tuples
Syntax:
Tuple_name=(item-1,item-2,…,ietm-n)
Eg:
>>> tup1=('hari','ravi',100,200)
>>> tup1
('hari', 'ravi', 100, 200)
>>> tup2=(1,2,3,4,5)
>>> tup2
(1, 2, 3, 4, 5)
>>> t=tuple('PYTHON')
>>> t
('P', 'Y', 'T', 'H', 'O', 'N')
Boolean:
The boolean data type is either True or False. In Python, boolean variables are
defined by the True and False keywords. Note the keywords True and False must
have an Upper Case first letter.
Eg:
a=True
b=False
Sets
A set is a collection of values(elements)with no duplicate elements.This is based
on a data structure known as a hash table. Sets support mathematical operations
like union, intersection, difference, and symmetric difference. Curly braces ( {} )or
the set() function can be used to create sets.
Syntax :
1)Set_name={item-1,item-2,..,item-n}
2)set_name = set([Sequence])
Eg:
>>> a={1,2,3,4,5}
>>> a
{1, 2, 3, 4, 5}
>>> b={1,2,3,1}
>>> b
{1, 2, 3}
>>> s1=set([3,2,5,1,4])
>>> s1
{1, 2, 3, 4, 5}
>>> s2=set((4,2,1,6,3))
>>> s2
{1, 2, 3, 4, 6}
>>> s3=set("WELCOME")
>>> s3
{'E', 'C', 'O', 'L', 'M', 'W'}
Dictionaries
Python dictionary is an unordered collection of items. Creating a dictionary is
placing items inside curly braces {} separated by comma. An item has a key and the
corresponding value expressed as a pair. Each key is separated from its value by a
colon ( key : value ).
Note: Dictionary is based on a data structure known as a hash table.
Syntax:
Dictionary_name = { key-1 : value-1, key-2 : value-2,….., key-n: value-n}
Eg1:
>>> d = {'a':10, 'b':1, 'c':22}
>>> d
{'a': 10, 'b': 1, 'c': 22}
Eg2:
>>> d = {'Name': 'Harsha', 'Age': 6, 'Class': 'First'}
>>> print (d['Name'])
Harsha
>>> print (d['Age'])
6
>>> print (d['Class'])
First
>>> type(10.0)
<class 'float'>
>>> type(‘abc’)
<class 'str'>
>>> type(True)
<class 'bool'>
>>> type(2+3j)
<class 'complex'>
Comments
Comments are text notes added to the program to provide explanatory
information about the source code. Un executable lines in a program are called as
comment lines. Comments lines are for documentation purposes and these lines
are ignored by the interpreter.
Python supports the following types of comments.
Single line comments
Multiline (Block)comments
Inline style comments
Docstring comments
Multi-Line Comments
Python does not provide the option for multiline comments. However, there are
different ways through which we can write multiline comments. We can multiple
hash(#) symbols to write multiline comments in Python.
Example
# Python program to demonstrate
# multiline comments
print("Multiline comments")
Python Docstrings
Python provides an in-built feature called docstrings for commenting on modules,
methods, functions, objects, and classes. Triple quotes (’’’) can be used to generate
multi-line comments,
Example:
’’’
This is a
Doc string comment
’’’
Python Input and Output
Python provides no. of built-in functions for I/O operations. Some of the
functions like input() and print() are widely used for standard input and output
operations . Let us see the output section first.
Python Output Using print() function
The 'print' function is used to print data to the standard output device(monitor) .
Syntax:
print(objects, sep=' ', end='\n')
a=5
print('The value of a is', a)
Output: The value of a is 5
print(1,2,3,4,5)
Output: 1 2 3 4 5
print(1,2,3,4,5,sep='*')
Output: 1*2*3*4*5
print(1,2,3,4,5,sep='#',end='$')
Output: 1#2#3#4#5$
python Input
We want to take the input from the user, We use input() function.
Syntax :
input([prompt])
Python Operators
Operator :
Operator is special symbol in Python and it performs a particular
operation.
Operand :
The value on which the operator acts is called as operand.
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication etc.
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
** Exponent
// Floor Division
Ari.py
print('Enter any two Numbers ')
a=int(input())
b=int(input())
print('Addition :',a+b)
print('Subtraction :',a-b)
print('Multiplication :',a*b)
print('Division :',a/b)
print('Modulus :',a%b)
print('Floor Division :',a//b)
print('Exponent :',a**b)
round()
Python provides an inbuilt function round() ,which rounds precision digits of
floating point number.
Syntax:
round(floating number, no of precision digits)
>>>round(10.639 , 2)
10.64
>>> round(10/3,2)
3.33
>>> n=10.3159
>>> n
10.3159
>>> round(n,2)
10.32
2)Relational operators
These are used to test the relation between 2 values or 2 expressions.
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
Logical operators :
These are used to combine the result of 2 or more expressions.
and Logical AND
or Logical OR
not Logical NOT
Bit-wise Operators :
These operators are used for manipulation of data at bit level.
Bit-wise logical operators :
These are used for bit-wise logical decision making.
& Bit-wise logical AND
| Bit-wise logical OR
Eg : a=5
b=6
a=5 - 1 0 1
b=6 - 1 1 0
1 0 1
1 1 0
----------------------
a&b : 1 0 0 =4
----------------------
1 0 1
1 1 0
----------------------
a|b : 1 1 1 =7
----------------------
1 0 1
1 1 0
----------------------
a^b : 0 1 1 =3
----------------------
Bit1.py
print('Enter any two Numbers ')
a=int(input())
b=int(input())
print('a & b :',a&b)
print('a | b :',a|b)
print('a ^ b :',a^b)
Hence it became,
1 0 0 0 0
1 0 0 0 0 = 2 power 4 = 16
1 0 0
Hence it became,
1 0
Bit2.py
a=4
b=a<<2
c=a>>1
print('a :',a)
print('b :',b)
print('c :',c)
Assignment Operators :
These operators are used to assign values to variables.
Simple assignment :
=
compound assignment
+=
-=
*=
/=
//=
%=
**=
Eg:
>>> n=10
>>> n
10
>>> n+=5
>>> n
15
Special operators
Python language offers two types of special operators. They are
1.identity operators
2.membership operators
Identity operators
‘is’ and ‘is not’ are the identity operators in Python. They are used to check two
values or variables.
eg:
>>> a=10
>>> b=10
>>> c=20
>>> a is b
True
>>> a is not c
True
Membership operators
‘in’ and ‘not in’ are the membership operators in Python.
They are used to test whether a value or variable is found in a sequence(string, list,
tuple,set,Etc.).
>>> st='abcd'
>>> 'a' in st
True
>>> 'k' not in st
True
>>> x='a'
>>> x in st
True
>>> "WEL" in "WELCOME"
True
>>> "WCE" in "WELCOME"
False
1)float(x) :
This function converts string type to a floating point number
2) int(x)
This function converts string type to integer.
Program
Conv1.py
4.chr(x) :
Converts an integer(Unicode value) to a character
5. str(x) :
Converts integer (or) float into a string.
6.complex(real,imag) :
Converts real numbers to complex number
Eg(Unicode values):
A to Z 65 to 90
a to z 97 to 122
0 to 9 48 to 57
Esc 27
Backspace 8
Enter 13
SpaceBar 32
Tab 9
etc.
program
Conv2.py
c = ord('A')
print ("After converting character to integer :",c)
c = chr(65)
print ("After converting integer to character :",c)
c = str(123)
print ("After converting integer to string :",c)
c = complex(1,2)
print ("After converting integers to complex number :",c)
Debugging
Debugging is the process of finding and fixing errors(bugs) in your code. Here
are some tools and techniques for debugging Python:
Python Debugger (PDB)
Debugging in Python is facilitated by pdb module (python debugger) which comes
built-in to the Python standard library. The major advantage of pdb is it runs purely
in the command line.
pdb supports:
Setting breakpoints
Stepping through code
Source code listing
Viewing stack traces
Starting Python Debugger
To start debugging within the program just insert import pdb,
pdb.set_trace() commands. Run your script normally.
Example
Debugging a Simple Python program of addition of numbers using Python pdb
module
import pdb
pdb.set_trace()
x = input("Enter first number : ")
y = input("Enter second number : ")
sum=x+y
print(sum)
Indentation
In Python, indentation is used to define blocks of code. It tells the Python
interpreter that a group of statements belongs to a specific block. All statements
with the same level of indentation are considered part of the same
block. Indentation is achieved using whitespace (spaces or tabs) at the
beginning of each line.
Selection
Conditional statments
1. simple if statement :
It is a conditional controlled statement and is used to control the flow of
execution.
Syntax :
if condition:
statements;
Flow Chart
2. if-else statement
It is an extension of simple if statement.
if condition :
if block
else :
else block
3. Nested if statement :
Using a if statement within another if is called as nested if. If a series of
decisions are involved, we use nested if statement.
Syntax:
if condition-1 :
if condition-2 :
Statement-1
else :
Statement-2
else :
if condition-3 :
Statement-3
else :
Statement-4
Flow Chart
Program:To find maximum of three values using nested if
Nest-if.py
4. if-elif-else statement
This statement is also used for a series of decisions are involved.
Syntax:
if condition-1 :
statements-1
elif condition-2 :
statements-2
………………….
………………….
elif condition-n:
statements-n
else :
else block - statements
In this statement, the conditions are evaluated from top to bottom, if the
condition is true then the statements associated that block is executed and the
control transfers to the next statement. Otherwise when all conditions are false then
the final else block statements will be executed.
Flow chart
Syntax:
while condition :
statements
In this loop first the condition will be evaluated. If it is true, then the
statement block will be executed. After the execution of statements, the
condition will be evaluated once again, if it is true then the statement block will
be executed once again. This process of repeated execution continues until the
condition becomes false.
range(x):
Returns a list whose items are consecutive integers from 0 to x-1 .
range(x, y):
Returns a list whose items are consecutive integers from x to y-1 .
range(x, y, step):
Returns a list of integers from x to y-1 , and the difference between each
successive value is the value defined by step.
Flow chart
#To Display Even and Odd numbers from 1 to given number using for loop
n=int(input("Enter any Number : "))
print("\nEven number from 1 to",n)
for i in range(2,n+1,2):
print(i,end='\t')
Infinite Loop
An infinite loop is a loop that executes its block of statements repeatedly until
the user forces the loop to quit.
break.py
To display Numbers from 1 to given number,if the given number is greater
than 20 it displays only 1 to 20 using break.
n=int(input("enter any Number :"))
k=1
while True :
print(k,end='\t')
k=k+1
if(k>20 or k > n ):
break
write a program to display numbers from 1 to 10 except for the values 4 and 7
using continue.
program
k=1
while k <=10 :
if k==4 or k==7:
k=k+1
continue
print (k,end=’\t’)
k=k+1
Output:
1 2 3 5 6 8 9 10
write a program to display numbers from 1 to 10 except for the values 4 and 7
using pass
pass.py
k=1
while k <=10 :
if k==4 or k==7:
pass
else:
print (k,end='\t')
k+=1
Output:
1 2 3 5 6 8 9 10
Nested Loops
A nested loop in python involves the inclusion of one loop with in another loop.
This construction allows for interacting over elements in multiple dimensions , such
as rows and columns of a matrix. By using nested loops, complex data structures
can be traversed efficiently. Nested loops in python can be used to solve problems
such as prime numbers in a given range, pattern printing, etc.
Prg:Write a Program to print prime numbers in a given range
patteren1
n=5
*****
*****
*****
*****
*****
n = int(input("Enter the value of n : "))
for i in range(1,n+1) :
for j in range(1,n+1):
print('*',end=' ')
print()
patteren2
n=5
*
**
***
****
*****
patteren3
n=5
1
22
333
4444
55555
n = int(input("Enter the value of n : "))
for i in range(1,n+1) :
for j in range(1,i+1):
print(i,end=' ')
print()
patteren4:
n=5
1
12
123
1234
12345
patteren5
n=5
*
* *
* * *
* * * *
* * * * *
Strings
A string is a sequence of characters used to store text information. A string can
be enclosed in single quotes (or) double quotes (or) triple quotes. By using triple
quotes we can write multi-line strings.
Eg:
st=' Hello World! '
st=" Hello World! "
st = '''Hello
Welcome To
Python Programming'''
Traversing a string
Traversing a string means accessing all the elements of the string one after the
other by using the index. A string can be traversed using for loop or while loop.
Example:
EX:
>>> st=”HELLO”
>>> print(st) # prints complete string
>>> print(s*2) #prints string 2 times
>>> print(st+”WORLD”) # prints concatenated string
slicing operator ‘:’ is used to access the individual characters of the string.
EX: st.py
# Given String
st = "ABCDEFGH"
# Start Oth index to end
print(st[0:])
# Starts 1th index to 4th index
print(st[1:5])
# Starts 2nd index to 3rd index
print(st[2:4])
# Starts 0th to 2nd index
print(st[:3])
#Starts 4th to 6th index
print(st[4:7])
o/p:
ABCDEFGH
BCDE
CD
ABC
EFG
String functions
str:
Returns a string representation of the specified object.
Syntax:
str(x)
x –dpyoae d caj ocecejbo
eg:
>>> str(123)
'123'
>>> str(10.345)
'10.345'
>>a=[1,2,3,4,5]
>>> str(a)
'[1, 2, 3, 4, 5]'
>>> k=str(a)
>>> k
'[1, 2, 3, 4, 5]'
>>> type(k)
<class 'str'>
max():
Returns the maximum alphabetical character in the string.
eg:
>>> max("ABCDEFGH")
'H'
min():
Returns the minimum alphabetical character in the string.
eg:
>>> min("ABCDEFGH")
'A'
len():
Counts and returns the number of characters in the string.
eg:
>>> len("ABCD")
4
sorted():
Returns the List representation string’ .s arcscaeoss na sdseoo dsoos
>>> st="CFADEB"
>>> sorted(st)
['A', 'B', 'C', 'D', 'E', 'F']
String Methods
lower():
Returns the string converted to lowercase.
eg:
>>> st="WelCome"
>>> st.lower()
'welcome'
upper():
Returns the string converted to uppercase.
eg:
>>> st="WelCome"
>>> st.upper()
'WELCOME'
capitalize()
Return a capitalized version of String, i.e. make the first character
have upper case and the rest lower case.
eg:
>>> st="welcome"
>>> st.capitalize()
'Welcome'
>>> s="abCDeFgH"
>>> s.capitalize()
'Abcdefgh'
swapcase():
Returns the string with uppercase characters converted to lowercase and
lowercase characters converted to uppercase .
Eg:
>>> st="WELcome"
>>> st
'WELcome'
>>> st.swapcase()
'welCOME'
title():
Returns the string with first character of each word converted to uppercase
characters and the rest all characters in lowercase.
eg:
>>> st="welcome to python programming"
>>> st
'welcome to python programming'
>>> st.title()
'Welcome To Python Programming'
isalpha():
Returns True if all characters in the string are alphabetic, otherwise returns
False.
eg:
>>> st="abcd"
>>> st.isalpha()
True
>>> st="123abcd"
>>> st.isalpha()
False
isdigit():
Returns true if all characters in the string are digits, otherwise returns false.
eg:
>>> st="123"
>>> st.isdigit()
True
>>> st="123abcd"
>>> st.isdigit()
False
islower():
Returns True if all characters(alphabets) in the string are lowercase, otherwise
returns False.
eg:
>>> st="abcd"
>>> st.islower()
True
>>> st="abcd123"
>>> st.islower()
True
>>> st="ABCD"
>>> st.islower()
False
>>> st="1234"
>>> st.islower()
False
>>> st="abcdABCD"
>>> st.islower()
False
isupper():
Returns true if all characters(alphabets) in the string are in uppercase, otherwise
returns false.
eg:
>>> st="ABCD"
>>> st.isupper()
True
>>> st="abcd"
>>> st.isupper()
False
>>> st="ABCD123"
>>> st.isupper()
True
>>> st="abcdABCD"
>>> st.isupper()
False
>>> st="1234"
>>> st.isupper()
False
spilt()
Return a list of the words in given string, using the specified 'sep'
syntax:
split(sep=' ')
eg:
>>> st="This is a Book"
>>> st.split()
['This', 'is', 'a', 'Book']
>>> st="abcd*123*ijkl*456"
>>> st.split(sep='*')
['abcd', '123', 'ijkl', '456']