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

PYTHON_UNIT1 & 2

Aktu unit 1 and unit 2

Uploaded by

akshatmishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

PYTHON_UNIT1 & 2

Aktu unit 1 and unit 2

Uploaded by

akshatmishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

SUBJECT-PYTHON PROGRAMMING

SUBJECT CODE- BCC302


FACULTY NAME – PRATEEK AGARWAL

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 1


• Python is a widely used general-purpose, high level programming
language.
• It was initially designed by Guido van Rossum in 1991 and
developed by Python Software Foundation.
• It was mainly developed for emphasis on code readability, and its
syntax allows programmers to express concepts in fewer lines of
code.
• Python is a programming language that lets you work quickly
and integrate systems more efficiently. There are two major
Python versions- Python 2 and Python 3.

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 2


Python IDE
• An IDE (Integrated Development Environment) is a software
application that helps programmers develop software code more
efficiently.

• An IDE combines many features into one place, such as editing,


building, testing, and packaging software.

• An IDE (Integrated Development Environment) is software


that combines commonly used developer tools into a compact
GUI (graphical user interface) application.
07-11-2024 PRATEEK AGARWAL PYTHON BCC302 3
• It is a combination of tools like a code editor, code compiler,
and code debugger with an integrated terminal.

Why are IDEs important?


Even a simple text editor like notepad can be used to write code.
However, IDEs offer some stunning features that go beyond
ordinary editing. By providing frequently used developer tools all
in one simple interface, one can directly get on to building their
applications

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 4


Why use Python
The following are the primary factors to use python in day-to-day
life:
1. Python is object-oriented Structure supports such concepts as
polymorphism, operation overloading and multiple inheritance.
2. Indentation is one of the greatest feature in python
3. It’s free (open source) Downloading python and installing
python is free and easy.
4. Python is a dynamically typed language. It doesn’t know about
the type of the variable until the code is run. So declaration is of
no use.
07-11-2024 PRATEEK AGARWAL PYTHON BCC302 5
5. . It’s Portable - Python runs virtually every major platform used
today As long as you have a compaitable python interpreter
installed, python programs will run in exactly the same manner,
irrespective of platform.

6. It’s easy to use and learn .

7. Interpreted Language - Python is processed at runtime by


python Interpreter

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 6


Python Install
Can Install Python from : http://python.org/downloads/

Now Let’s code First Program Hello World

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 7


First Program :
On cmd (command prompt)

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 8


On Notepad
• Open Notepad and type code and save using .py extension in
computer drive (suppose in C Drive and P name folder)

• now open cmd and type

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 9


On VScode:
• Open terminal and simply open new folder and create new file in it
and type
print(“hello world”) and run the program.

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 10


• Output :

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 11


Python Indentation :
• Indentation refers to the spaces at the beginning of a code line.
• Where in other programming languages the indentation in code
is for readability only, the indentation in Python is very
important.

Eg is on next page

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 12


07-11-2024 PRATEEK AGARWAL PYTHON BCC302 13
• If you skip an
indentation ,
the python will
give error :

See Terminal :
Showing error
In line 2

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 14


• You have to use the same number of spaces in the same block of code,
otherwise Python will give you an error:

• Output :

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 15


Python Variables

• In Python, a variable is a container that stores data


values. Variables are created when you assign a value to them,
and you don't need a separate command to declare them.

• A Python variable may be assigned a value of one type an then


later re-assigned a value of a different type . For example ,
X =“apple” can later be X = 5 .

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 16


Example :

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 17


You can get the data type of a variable with
the type() function

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 18


• String variables can be declared either by using single ,double or
triple quotes:

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 19


• Variable names are case-sensitive.

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 20


Variable Names
• A variable can have a short name (like x and y) or a more
descriptive name (age, carname, total_volume). Rules for Python
variables:A variable name must start with a letter or the
underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three
different variables)
• A variable name cannot be any of the Python keywords.
07-11-2024 PRATEEK AGARWAL PYTHON BCC302 21
• Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John“

• Illegal variable names:


2myvar = "John"
my-var = "John"
my var = "John"

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 22


• In print() function , multiple variable output are separated by a
comma :

• Can also use + operator to output multiple variable :

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 23


Python Variables - Assign Multiple Values
Python allows you to assign values to multiple variables in one line:

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 24


One Value to Multiple Variables

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 25


• If you have a collection of values in a list, tuple etc. Python allows you
to extract the values into variables. This is called unpacking.

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 26


Python Operators
• Operators are used to perform operations on variables and
values.
Python divides the operators in the following groups:
> Identity operators
> Membership operators
> Bitwise operators

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 27


ARITHMETIC OPERATORS :

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 28


Relational Operators :

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 29


• ASSIGNMENT OPERATOR

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 30


• Logical
Operators :

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 31


Data Types in Python
• In programming, data type is an important concept.
• Variables can store data of different types, and different types can
do different things.
• Python has the following data types built-in by default, in these
categories :
Text Type: str
Numeric int, float, complex
Types:
Sequence list, tuple, range
Types:
07-11-2024 PRATEEK AGARWAL PYTHON BCC302 32
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryvi
ew

None Type: NoneType

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 33


Numberic Type
There are three numeric types in Python:

• Int = Int, or integer, is a whole number, positive or negative,


without decimals, of unlimited length.
eg: x = 1
y = 35656222554887711
z = -3255522

• Float = Float, or "floating point number" is a number, positive


or negative, containing one or more decimals.
eg: x = 1.1 , y = 1.0 , z = -35.59
25/9/2024 PRATEEK AGARWAL PYTHON BCC302 34
• Float can also be scientific numbers with an "e" to indicate the
power of 10.
Eg : x = 35e3
y = 12E4
z = -87.7e100

• Complex = Complex numbers are written with a "j" as the


imaginary part
Eg : x = 3+5j
y = 5j
z = -5j

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 35


Python Strings
• Strings in python are surrounded by either single quotation
marks, double quotation marks or triple quotation marks.
Eg: 'hello' is the same as "hello".
Can display string literal with print() function ie; print("Hello").
• Like many other popular programming languages, strings in
Python are arrays of bytes representing unicode characters.
• However, Python does not have a character data type, a single
character is simply a string with a length of 1

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 36


• Square brackets can be used to access elements of the string
Get the character at position 1 (remember that the first character has
the position 0):

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 37


String Length
To get the length of a string, use the len() function.

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 38


Check String
• To check if a certain phrase or character is present in a string, we can
use the keyword in .
Example :Check if "free" is present in the following text:

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 39


07-11-2024 PRATEEK AGARWAL PYTHON BCC302 40
07-11-2024 PRATEEK AGARWAL PYTHON BCC302 41
Python - Slicing Strings
• You can return a range of characters by using the slice syntax.
• Specify the start index and the end index, separated by a
colon, to return a part of the string.

Eg : next slide

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 42


07-11-2024 PRATEEK AGARWAL PYTHON BCC302 43
• Slice From the Start
b = "Hello, World!"
print(b[:5])

• Slice To the End


b = "Hello, World!"
print(b[2:])

• Negative Indexing
b = “ankita!“ b=“ankita!”
print(b[-5:-2]) output: kit eg:- print(b[2,-2])
07-11-2024 PRATEEK AGARWAL PYTHON BCC302 44
07-11-2024 PRATEEK AGARWAL PYTHON BCC302 45
Few more methods can be used in string
are :

Remove Whitespace : The strip() method removes any


whitespace from the beginning or the end

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 46


• Replace String

• Split String : The split() method splits the string into substrings if
it finds instances of the separator

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 47


07-11-2024 PRATEEK AGARWAL PYTHON BCC302 48
07-11-2024 PRATEEK AGARWAL PYTHON BCC302 49
String Concatenation
• To concatenate, or combine, two strings you can use the + operator

• . To add a space between them, add a " “

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 50


• F-String was introduced in Python 3.6, and is now the preferred way
of formatting strings.

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 51


What are Mutable Data Types?
Mutable objects are those that allow you to change their value
or data in place without affecting the object’s identity.

What are Immutable Data Types?


immutable objects don’t allow this kind of operation. You’ll
just have the option of creating new objects of the same type
with different values.

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 52


List :
• Lists are used to store multiple items in a single variable. Lists are
one of built-in data types in Python used to store collections of
data.

• List items are ordered, changeable, and allow duplicate values.


• List items are indexed, the first item has index [0], the second
item has index [1] etc
07-11-2024 PRATEEK AGARWAL PYTHON BCC302 53
• List Length
To determine how many items a list has, use the len() function:

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 54


Tuple :
• Tuples are used to store multiple items in a single variable.
• A tuple is a collection which is ordered and unchangeable

• Tuples are written with round brackets. Tuple items are ordered,
unchangeable, and allow duplicate values.
• Tuple items are indexed, the first item has index [0], the second
item has index [1] etc.

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 55


• Tuples are unchangeable, meaning that we cannot change, add
or remove items after the tuple has been created.

• To determine how many items a tuple has, use the len() function:

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 56


• Create Tuple With One Item

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 57


• A tuple can contain different data types:
Eg - tuple1 = ("abc", 34, True, 40, "male“)
Access Tuple Items

Negative indexing means start from the end.


-1 refers to the last item, -2 refers to the second last item etc.

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 58


Change Tuple Values
• Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable as it also is called.
• But there is a workaround. You can convert the tuple into a list,
change the list, and convert the list back into a tuple.

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 59


Example
• Convert the tuple into a list, add "orange", and convert it back into a
tuple:
Since tuples are immutable, they do not have a built-in append()
method, but you can convert it into a list, add your item(s), and convert
it back into a tuple.

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 60


• Add tuple to a tuple. You are allowed to add tuples to tuples, so if you
want to add one item, (or many), create a new tuple with the item(s), and
add it to the existing tuple:
Example
Create a new tuple with the value "orange", and add that tuple:

thistuple = ("apple", "banana", "cherry")


y = ("orange",)
thistuple += y
print(thistuple)

O/P : ('apple', 'banana', 'cherry', 'orange')

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 61


• Tuples are unchangeable, so you cannot remove items from it, but
you can use the same workaround as we used for changing and
adding tuple items:
Example :
Convert the tuple into a list, remove "apple", and convert it back into a
tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)

O/P: ('banana', 'cherry')

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 62


Unpacking a Tuple
• When we create a tuple, we normally assign values to it. This is called
"packing" a tuple:

• But, in Python, we are also allowed to extract the values back into
variables. This is called "unpacking":

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 63


07-11-2024 PRATEEK AGARWAL PYTHON BCC302 64
Using Asterisk*
• If the number of variables is less than the number of values, you can
add an * to the variable name and the values will be assigned to the
variable as a list:

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 65


If the asterisk is added to another variable name than
the last, Python will assign values to the variable until
the number of values left matches the number of
variables left.

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 66


Dictionary in Python
• A Python dictionary is a data structure that stores the value in
key: value pairs, which makes it easier to find values.
Example:

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 67


• Python Dictionary Syntax
dict_var = {key1 : value1, key2 : value2, …..}

• In Python, a dictionary can be created by placing a sequence of


elements within curly {} braces, separated by a ‘comma’.

• Dictionary keys are case sensitive, the same name but different
cases of Key will be treated distinctly.

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 68


• Different Ways to Create a Python Dictionary

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 69


• Output :

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 70


Accessing Items
• You can access the items of a dictionary by referring to its
key name, inside square brackets:

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 71


• There is also a method called get() that will give you the
same result

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 72


• The keys() method will return a list of all the keys in the
dictionary.

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 73


• Add a new item to the original dictionary, and see that the keys list gets
updated as well:

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 74


• The values() method will return a list of all the values in the
dictionary.
x = thisdict.values()

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 75


07-11-2024 PRATEEK AGARWAL PYTHON BCC302 76
07-11-2024 PRATEEK AGARWAL PYTHON BCC302 77
To determine if a specified key is present in a
dictionary use the in keyword:

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 78


Range()
• The Python range() function returns a sequence of numbers,
in a given range. The most common use of it is to iterate
sequences on a sequence of numbers using Python loops.

for i in range(5):
print(i, end=" ")
print()

Output:

01234
07-11-2024 PRATEEK AGARWAL PYTHON BCC302 79
Syntax of Python range() function
Syntax: range(start, stop, step)
Parameter :
start: [ optional ] start value of the sequence
stop: next value after the end value of the sequence
step: [ optional ] integer value, denoting the difference
between any two numbers in the sequence.

Return : Returns an object that represents a sequence of


numbers
07-11-2024 PRATEEK AGARWAL PYTHON BCC302 80
Example of Python range (start, stop)
• In this example, we are printing the number from 5 to 19.
We are using the range function in which we are passing the
starting and stopping points of the loop.
# printing a natural
# number from 3 to 6 or
for i in range(3, 20):
print(i, end=" ")
Output: 3 ,4 ,5

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 81


Example of Python range (start, stop, step)
printing the number from 0 to 9 with the jump of 2.

for i in range(0, 10, 2):


print(i, end=" ")
print()
Output:

02468
07-11-2024 PRATEEK AGARWAL PYTHON BCC302 82
Python range() using Negative Step
If a user wants to decrement, then the user needs steps to be
a negative number.
# incremented by -2
for i in range(25, 2, -2):
print(i, end=" ")
print()
Output :
25 23 21 19 17 15 13 11 9 7 5 3
07-11-2024 PRATEEK AGARWAL PYTHON BCC302 83
Mutable and Immutable Data Types :
• Every variable in Python holds an instance of an object. There are two
types of objects in Python i.e. Mutable and Immutable objects.

****When an object is instantiated (created) in a programming


language like Python, Java, or C++, it is assigned a unique identifier,
known as an object ID (An object ID is a value that uniquely identifies
an object at runtime,. It represents the memory location where the
object is stored.) *****

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 84


Even though
x and y holds
same data ,
they will have
different
object ids
because they
are distinct
objects

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 85


Question:

Q.1> Explain why program generates an error


• x= ['12','hello',456]
• x[0]*=3
• x[1][1]='bye‘

Q.2> Python program to print even length words in a string

07-11-2024 PRATEEK AGARWAL PYTHON BCC302 86


07-11-2024 PRATEEK AGARWAL PYTHON BCC302 87

You might also like