0% found this document useful (0 votes)
2 views

BCA 402 Python Unit 1

This document provides an overview of Python programming, including its history, features, applications, and limitations. It covers various data types, such as numeric, sequence, boolean, set, and dictionary, along with their creation and usage. Additionally, it discusses operators, control flow statements, and built-in functions in Python.

Uploaded by

varun.gupta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

BCA 402 Python Unit 1

This document provides an overview of Python programming, including its history, features, applications, and limitations. It covers various data types, such as numeric, sequence, boolean, set, and dictionary, along with their creation and usage. Additionally, it discusses operators, control flow statements, and built-in functions in Python.

Uploaded by

varun.gupta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

Python (Unit-

I) BCA-402

Programme: BCA Course: Python Programming


Overview:
Introduction to Python Programming :

Python : python is general purpose dynamically type high level


programming language developed by “Guido Van Rossum” in the year
1991 at CWI in Netherland.
Syntax:
Print(“Neelima”)

Why name Python?


Guido Van Rossum was a fan of the popular comedy show “Monty python’s flying
Circus” broadcasted by BBC (1969-74),So he decided to pick the name his language as
python.
Features :
1. Simple & Easy
2. Freeware & Open Source
3. Platform Independent
4. Rich Library
5. Portable
6. Embedded
7. Extensible
8. Interpreted

Applications:
1. Web Development
2. Game Development
3. IOT Programming
4. Machine Learning
5. AI
6. DB Programming
7. Network Programming

Limitations:
1. Mobile Application is not possible through python
2. Performance is not upto the mark
Installations Steps :
Step - 1: Select the Python's version to download.
Step - 2: Click on the Install Now.
Step - 3 Installation in Process.
Step - 4: Verifying the Python Installation.
Step - 5: Opening idle.

Python Data Types :


Data types represents the different kinds of values that we stored on the variable.
Note: we don’t need to specify the data type explicitly based on values type allocated
automatically.
Numeric Data Types : The numeric data type in Python represents the
data that has a numeric value. A numeric value can be an integer, a
floating number, or even a complex number. These values are defined as
Python int, Python float and Python complex classes in Python.

Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an integer
value can be.

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. Optionally, the character e or E followed by
a positive or negative integer may be appended to specify scientific notation.

Complex Numbers – Complex number is represented by a complex class. It is specified


as (real part) + (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.
# Python program to
# demonstrate numeric value

a=5
print("Type of a: ", type(a))

b = 5.0
print("\nType of b: ", type(b))

c = 2 + 4j
print("\nType of c: ", type(c))

Output:

Type of a: <class 'int'>

Type of b: <class

'float'>

Type of c: <class 'complex'>


Sequence Data Type:

The sequence Data Type in Python is the ordered collection of similar or


different data types. Sequences allow storing of multiple values in an
organized and efficient fashion. There are several sequence types in
Python –

❖ Python String
❖ Python List
❖ Python Tuple

Python String:
A string is a collection of one or more characters put in a single quote, double-quote, or
triple-quote. In python there is no character data type, a character is a string of length one.
It is represented by str class.

Creating String
Strings in Python can be created using single quotes or double quotes or even triple
quotes.
# Python program to
# demonstrate string value

a = ‘Neelima’
print("Type of a: ", type(a))

b = “Neelima Rai” print("\


nType of b: ", type(b))

c =‘’’Neelima Thakur Rai’’’


print("\nType of c: ", type(c))

Output:

Type of a: <class ‘str’>


Type of b: <class ‘str'>
Type of c: <class ‘str'>
List Data Type
Lists are just like arrays, declared in other languages which is an ordered
collection of data. It is very flexible as the items in a list do not need to be of
the same type.
Creating List
Lists in Python can be created by just placing the sequence inside the square
brackets[].
# Creating a List with
# the use of multiple values

List = [“Ms.", “Thakur", “Neelima"] print("\


nList containing multiple values: “)
Print(List[0])
Print(List[2])
Print(type(List))

Output:
List containing multiple values:
Ms.
Neelima
<class ‘List’>
Tuple Data Type:
Just like a list, a tuple is also an ordered collection of Python objects.

The only difference between a tuple and a list is that tuples are immutable i.e. tuples cannot
be modified after it is created. It is represented by a tuple class.
Creating a Tuple

In Python, tuples are created by placing a sequence of values separated by a ‘comma’ with or
without the use of parentheses for grouping the data sequence. Tuples can contain any number
of elements and of any datatype (like strings, integers, lists, etc.)
# Creating a Tuple
# with nested
tuples Tuple1 =
(5,55,10)
Print(type(Tuple1))

Output:

<class ‘Tuple1’>
Boolean Data Type:

Data type with one of the two built-in values, True or False. Boolean objects
that are equal to True are truthy (true), and those equal to False are falsy (false).
But non-Boolean objects can be evaluated in a Boolean context as well and
determined to be true or false. It is denoted by the class bool.

Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise
python will throw an error.

# Python program to
# demonstrate boolean type

print(type(True))
print(type(False))
print(type(true))

Output:
<class 'bool'>
<class 'bool'>
NameError: name 'true' is not defined
Set Data Type :
In Python, a Set is an unordered collection of data types that is iterable, mutable
and has no duplicate elements. The order of elements in a set is undefined though
it may consist of various elements.

Create a Set in Python


Sets can be created by using the built-in set() function with an iterable object or a
sequence by placing the sequence inside curly braces, separated by a ‘comma’.
The type of elements in a set need not be the same, various mixed-up data type
values can also be passed to the set.

# Creating a Set with


# a mixed type of values
# (Having numbers and strings)
set1 = set([1, 2, ‘Nisha', 4.5, ])
print(set1(type(set1))

Output:
{1, 2,‘Nisha', 4.5}<class ‘set’>
Dictionary Data Type in Python

A dictionary in Python is an unordered collection of data values, used to store


data values like a map, unlike other Data Types that hold only a single value as an
element, a Dictionary holds a key: value pair. Key-value is provided in the
dictionary to make it more optimized. Each key-value pair in a Dictionary is
separated by a colon : , whereas each key is separated by a ‘comma’.

Create a Dictionary

In Python, a Dictionary can be created by placing a sequence of elements within


curly {} braces, separated by ‘comma’. Values in a dictionary can be of any data
type and can be duplicated, whereas keys can’t be repeated and must be
immutable. The dictionary can also be created by the built-in function dict(). An
empty dictionary can be created by just placing it in curly braces{}.

Note – Dictionary keys are case sensitive, the same name but different cases of
Key will be treated distinctly.
# Creating a Dictionary

Dict = {1: ‘Welcome', 2: ’MMDU', 3: ‘BCA’}


print("\nDictionary with the use of Integer Keys: ")
print(Dict)

Output:
Dictionary with the use of Integer Keys:
{1: ‘Welcome', 2: ‘MMDU', 3: ‘BCA'}
Variable : A variable is a container in which a value is store and that
value is change during the execution time. For ex a=10, b=5.5 etc.

Keywords: Keywords are reserved words whose meaning already defined


in the python interpreter.
Note:
• We can not use a keyword as a variable name, method name or
any other identifier.
• Python Keywords are the case sensitive
• 35 Keywords are in python.

Identifier:
• Identifier is the name of anything in a program like variable
name, function name, class name, object name etc.
• Identifier is a collection of valid characters that identifies something.
Construction Rule for Identifier:

1. Any combination of alphabets, digits and underscore.


2. Any special symbol is not allowed except underscore.
3. It can not be start with digit.
4. It can be used any keyword.

Literals/Constant:
Literals are constants that are self-explanatory and don’t need to be
computed or evaluated.
1. Number Literals:12,55.5
2. Boolean Literals: True, False
3. Special Literals: None
4. Collection Literals: list, tuple, dictionary
Operators in python:

• OPERATORS: These are the special symbols. Eg - + , * , /, etc.


• OPERAND: It is the value on which the operator is applied.

Types of Operators in Python


1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators and Membership Operators
# Examples of Arithmetic Operator Output:
a=9 13
b=4 5
# Addition of numbers 36
add = a + b 1
# Subtraction of numbers 6561
sub = a - b
# Multiplication of number
mul = a * b
# Modulo of both number
mod = a % b
# Power
p = a ** b
print(add)
print(sub)
print(mul)
print(mod)
print(p)
# python program to demonstrate the use of "/"
print(5/5)
print(10/2)
print(-10/2)
print(20.0/2)
Output:
1.0 5.0 -5.0 10.0

# python program to demonstrate the use of "//"


print(10//3)
print (5.0//2)

Output:
3 2.0
Examples of Relational Operators/Comparision

a = 13 Output:
b = 33 False True False True

# a > b is False False


print(a > b)

# a < b is True
print(a < b)

# a == b is False
print(a == b)

# a != b is True
print(a != b)

# a >= b is False
print(a >= b)

# a <= b is True
print(a <= b)
Logical Operators in python is as follows:

1. Logical not
2. logical and
3. logical or

# Examples of Logical Operator Output:


a = True False
b = False True
False
# Print a and b is False
print(a and b)

# Print a or b is True
print(a or b)

# Print not a is False


print(not a)
Assignment Operators in Python
# Examples of Assignment Operators Output:
10 20 10 100
a = 10
# Assign
value b = a
print(b)
# Add and assign value
b += a
print(b)
# Subtract and assign value
b -= a
print(b)
# multiply and assign
b *= a
print(b)
Identity Operators in Python

In Python, is and is not are the identity operators both are used to check if two
values are located on the same part of the memory. Two variables that are
equal do not imply that they are identical.
• is True if the operands are identical
• is not True if the operands are not identical .

Example of Identity Operators in Python.


a = 10
b = 20
c=a
print(a is not b)
print(a is c)

Output
True True
Membership Operators in Python
In Python, in and not in are the membership operators that are used to
test whether a value or variable is in a sequence.
• in True if value is found in the sequence
• not in True if value is not found in the
sequence # Python program to illustrate
# not 'in' operator
list = [10, 20, 30, 40, 50]
10 in list
Output:
True
list=[5,10,15,20]
10 not in
list Output
False
Bitwise Operators in Python
Python Bitwise operators act on bits and perform bit-by-bit operations.
These are used to operate on binary numbers.

The precedence of Bitwise Operators in python is as follows:


• Bitwise NOT
• Bitwise Shift
• Bitwise AND
• Bitwise XOR
• Bitwise OR
# Examples of Bitwise operators Output:
a = 10 0 14 -11 14 2 40
b=4

# Print bitwise AND operation


print(a & b)
# Print bitwise OR operation
print(a | b)
# Print bitwise NOT operation
print(~a)
# print bitwise XOR operation
print(a ^ b)
# print bitwise right shift operation print(a
>> 2)
# print bitwise left shift operation
print(a << 2)
Python Comments:

Comments in Python are the lines in the code that are ignored by
the interpreter during the execution of the program.
There are three types of comments in Python:

1. Single line
Comments # sample
comment
# Python program to demonstrate

2. Docstring Comments

""" Python program to demonstrate


multiline comments"""
Control Flow Statement:
Conditional Statement

1) If Statement :
An "if statement" is written by using the if keyword.
E.g:
a = 33
b = 200
if b > a:
print("b is greater than a")
2)If-Else Statement:

a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
3)El-if Statement:

a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Iterative Statement

Loops :
It provides the two types of loops to handle looping requirements.

1) While Loop:
Syntax:
i) for var_name in range(start
,end): Statements

2) For Loop:
Syntax:
ii) while condition :
Statement
#Example to illustrate the for loop:

user_input=int(input( “enter a number= ”))


for num in range(1,11):
print(user_input * num)

Output:
Enter a
number=5 5
10
15
20
25
30
35
40
45
50
#Example to illustrate the while loop:
password = “ Neelima”
input_password = input(“Enter Password= ”)
while password != input_password:
input_password = input(“Enter password= ” )
else:
print(“ Unlocked!! ”)

Output:
Enter Password= Neelima
Unlocked!!
Transfer Statement

Continue ,break Statement :


Break: A break statement in Python alters the flow of a loop by
terminating it once a specified condition is met.
Continue: The continue statement in Python is used to skip the remaining code
inside a loop for the current iteration only.

#Break Statement
for num in
range(1,11): if num
%2==0;
break
else:
print(num)
Output:
1
#Example of continue statement:

for num in range(1,11):


if num%2==0:
continue
else:
print(num)
Output:
1
3
5
7
9
Pass Statement:
The pass statement is used as a placeholder for future code.
When the pass statement is executed, nothing happens, but you avoid getting
an error when empty code is not allowed.
Empty code is not allowed in loops, function definitions, class definitions, or
in if statements.

a = 33
b = 200
If b > a:
pass
Output:
# having an empty if statement like this, would raise an error without the pass
statement
Python Build In Function :

1. print()
#it will display the statement written within print statement

2. input()
# If we want to take input from user then input function is used.

3. type()
#it will tell the type of data
. For ex.
var a=15
print(type(a))
Output:
<class:’int’>
4. int()
#The int() function returns the numeric integer equivalent from a
given expression.
# int() on string representation of numbers
print("int('9')) =", int('9'))
Output:
int('9')) = 9

5. abs()
#The abs() function return the absolute
value abs(-4)
Output
4

6. pow()
#It will return the power of value .for example
pow(2,2)
◻ 4
6. min / max()
#It will return min and max value from the list
min([6,5,3,8,9])
Output
3

7. round()
#The round() function returns a floating point number that is a rounded version
of the specified number, with the specified number of decimals.
var c=22/7
print(c)
round(c,2)
output
3.14
8. divmod()
#It return division integer and remainder value respectively
divmod(5,2)
output
(2,1)

9. bin()
#It wil return the binary value for respective number.
bin(4)
Output
(0100)

10. Id()
#It will return the memory location where the variable is store.
a=5
id(a)
14078##9833
11. len()
#It will return the length of the given string .
len(“SHIFA”)
Output
5

12. sum()
#It will add the all integers present in the list.
Sum({5,4,2,3,1})
Output
15

13. help()
#If we want to know the detail of any function then we can use the function
help.
help(“sum”)
Output
It will describe sum function
Strings

• String is a sequence of characters


• String may contain alphabets, numbers and special characters.
• Usually strings are enclosed within a single quotes, double quotes and triple quotes.
• Strings are immutable in nature.
• Example:
a= ‘Hello World’
b=“Python”
c=‘’’BCA’’’

Strings Are Immutable

• Strings are immutable character sets.


• Once a string is generated you cannot change any character within the string.
Creating String

o Strings are versatile and can be created


using single, double, or triple quotes.
o Concatenation and repetition are basic
operations for manipulating strings.
o Formatting allows you to create

dynamic and readable string outputs.


String Indexing

• Zero-Based Indexing: Access characters starting from 0.


• Negative Indexing: Access characters from the end using negative indices.
• Index Out of Range: Accessing out-of-range indices raises IndexError.
• Immutability: Strings cannot be modified by indexing.
• Indexing with Slicing: Combine indexing with slicing to extract substrings.
String Slicing

• Slicing operation is used to return / select / slice the particular substring based on
the user requirements.
• A segment of string is called slice.
• Syntax: string_variablename [start: end]
String Comparison

• We can compare to strings using comparison operator such as ==,!=,<,<=,>,>=


• Python compare strings on their corresponding ASCII values.
• String Comparison returns Boolean values as Output.
String Manipulation

• Concatenation: Combining two strings.


• Repetition: Repeating the same string.
• Slicing: Extracting substrings with different indices.
• Stripping: Removing leading and trailing whitespace.
• Changing Case: Converting to upper, lower, and title case.
• Replacing: Substituting one substring for another.
• Finding: Locating the position of a substring.
• Splitting: Breaking the string into a list of substrings.
• Joining: Combining a list of substrings into a single string.
• Formatting: Inserting variables into a formatted string.
• Checking: Verifying if a substring exists.
• Aligning: Adjusting text alignment with padding.
Inbuilt String Functions
• There are mainly 3 inbuilt functions:
– len(): Used to calculate number
of characters in string.
– max(): Used to find character
with highest Unicode value in
string.
– min(): Used to find character
with lowest Unicode value in
string..
String Functions And Methods

You might also like