0% found this document useful (0 votes)
8 views496 pages

PythonByBhupi (1)

This document provides an introduction to Python programming, detailing its history, features, and applications. Python is highlighted as a beginner-friendly, high-level language widely used in various fields including web development and machine learning. It covers syntax, keywords, data types, and operators, along with installation instructions and the use of integrated development environments (IDEs).

Uploaded by

royalka12345
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)
8 views496 pages

PythonByBhupi (1)

This document provides an introduction to Python programming, detailing its history, features, and applications. Python is highlighted as a beginner-friendly, high-level language widely used in various fields including web development and machine learning. It covers syntax, keywords, data types, and operators, along with installation instructions and the use of integrated development environments (IDEs).

Uploaded by

royalka12345
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/ 496

Introduction to Python

What is Programming

 Programming is the mental process of thinking up instructions to


give to a machine (like a computer).

 Programming is a collaboration between humans and computers.

 Programming, also known as coding, refers to the process of


writing instructions for computing devices and systems. A
computer program translates those instructions into a language
that computers can understand.
Python

 Python is a general purpose high level programming language.

 Python was developed by Guido Van Rossum in 1989 while working


at National Research Institute at Netherlands.

 But officially Python was made available to public in 1991. The


official Date of Birth for Python is : Feb 20th 1991.

 Python is recommended as first programming language for


beginners.
Python

 Python is a high-level, general-purpose and a very popular


programming language. Python programming language (latest
Python 3) is being used in web development, Machine Learning
applications, along with all cutting edge technology in Software
Industry. Python Programming Language is very well suited for
Beginners, also for experienced programmers with other programming
languages like C++ and Java.
Why

• While Guido van Rossum was implementing Python, he was also


reading the published scripts from Monty Python’s Flying Circus.

• Monty Python’s Flying Circus is a BBC Comedy TV series from the


year 1969+. It is a highly viewed TV series and is rated 8.8 in
IMDB.

• Python programming language is highly rated too. According to a


recent Stackoverflow survey, Python has overtaken Java in
popularity.
Why
Why
Why

 Python works on different platforms (Windows, Mac, Linux, Raspberry


Pi, etc).

 Python has a simple syntax similar to the English language.

 Python has syntax that allows developers to write programs with


fewer lines than some other programming languages.

 Python language is being used by almost all tech-giant companies like


– Google, Amazon, Facebook, Instagram, Dropbox, Uber… etc.
Why

Internally Google and You tube use Python coding


NASA and New York Stock Exchange Applications developed
by Python.
Top Software companies like Google, Microsoft, IBM, Yahoo
using Python.
16 Famous Companies that uses PYTHON
Where
Where

1. For developing Desktop Applications


2. For developing web Applications
3. For developing database Applications
4. For Network Programming
5. For developing games
6. For Data Analysis Applications
7. For Machine Learning
8. For developing Artificial Intelligence Applications
9. For IOT
Syntax

• Python was designed for readability, and has some similarities to the
English language with influence from mathematics.

• Python uses new lines to complete a command, as opposed to other


programming languages which often use semicolons or parentheses.

• Python relies on indentation, using whitespace, to define scope; such


as the scope of loops, functions and classes. Other programming
languages often use curly-brackets for this purpose.
Syntax

JAVA C PYTHON
Syntax

JAVA C PYTHON
Pre Requisites

PRE
• There are no prerequisites to learn Python but a little bit of REQUISISTES
knowledge of any programming language like what is a loop, what
if and else does, how operators are used. If you know the basics of
any programming language, it would be easy to learn Python.

• You should have a basic understanding of Computer Programming


terminologies. A basic understanding of any of the programming
languages is a plus.
1 EASY 4 HIGH LEVEL

2 EXPRESSIVE 5 EXTENSIVE LIBRARY

3 OPEN SOURCE 6 DYNAMICALLY TYPED

7 PLATFORM INDEPENDENT
EASY
Python
Python is a simple programming language. When we read Python
program, we can feel like reading English statements.
The syntaxes are very simple and only 30+ keywords are available.
When compared with other languages, we can write programs with very
less number of lines. Hence more readability and simplicity.
We can reduce development and cost of the project.
Python is an expressive language. Expressive in this
context means that a single line of Python code can do more than a
Open
single line of code in most other languages. The advantages of a more Source
expressive language are obvious – the fewer lines of code you write, the
faster you can complete the project

We can use Python software without


any license and it is freeware.
Its source code is open, so that we can we can customize based on our
requirement.
Python is high level
programming language and hence it is programmer friendly language.
Being a programmer we are not required to concentrate low level
activities like memory management and security etc..

Once we write a Python program, it can run


on any platform without rewriting once again.
Internally PVM is responsible to convert into machine understandable
form.
In Python we are not required to declare type
for variables. Whenever we are assigning the value, based on value,
Huge
type will be allocated automatically. Hence Python is considered Libraries
as dynamically typed language.
But Java, C etc are Statically Typed Languages b'z we have to provide
type at the beginning only.

Python has a rich inbuilt library.


Being a programmer we can use this library directly and we are not
responsible to implement the functionality.
We discussed above that Python is an interpreted language and
dynamically-typed language. The line by line execution of code often
leads to slow execution.

It is very rarely used for mobile development. Python is not a very good
language which means it is a weak language for mobile development.
Dynamically Typed- In Python we are not required to declare type for
variables. Whenever we are assigning the value, based on value, type
will be allocated automatically. Hence Python is considered
as dynamically typed language.
But Java, C etc are Statically Typed Languages b'z we have to provide
type at the beginning only.

Extensive Library- Python has a rich inbuilt library.


Being a programmer we can use this library directly and we are not
responsible to implement the functionality.
Python is a Case Sensitive Language that means Uppercase and
Lowercase letters would be treated differently.

Anything that is case sensitive discriminates between uppercase and


lowercase letters. In other words, it means that two words that appear or
sound identical but are using different letter cases, are not considered
equal.

Example – Your password is case-sensitive, it must be written in a


particular form using all capital letters or all small letters.
Python 1.0V introduced in Jan 1994
Python 2.0V introduced in October 2000
Python 3.0V introduced in December 2008

Note: Python 3 won't provide backward compatibility to Python2


i.e. there is no guarantee that Python2 programs will run in Python3.
Current versions

Python 3.10.4 : Latest


Python is a widely used high-level programming language. To write and
execute code in python, we first need to install Python on our system.

Installing Python on Windows takes a Bunch of Seconds

Step 1 : - Go to https://www.python.org/downloads/
Step 2 : - There you will see the Latest version of Python as of now it is
3.10.4
Step 3 : - Click on Download Now
Now the Python Executable Controller is downloaded simply install it
An integrated development environment (IDE) is a software application
that provides comprehensive facilities to computer programmers for
software development. An IDE normally consists of at least a source
code editor, build automation tools and a debugger.
An IDE (or Integrated Development Environment) is a program
dedicated to software development. As the name implies, IDEs integrate
several tools specifically designed for software development. These tools
usually include:

• An editor designed to handle code (with, for example, syntax


highlighting and auto-completion)
• Build, execution, and debugging tools
• Some form of source control
Most Popular IDE as follows

Netbeans
Pycharm
Eclipse
Integrated
Jupiter Development
Spyder Environment
Dev
IntelliJ
Here, We are using Pycharm and inbuilt IDLE throughout our course but
you can choose any IDE of your choice.

Steps to install -

1. Google it and download it from a trusted website


2. Then setup will download and install it in your PC/Laptop
3. Here is the icon automatically created in your Desktop Screen.
Before starting working with Python, a specific path is to set.

Your Python program and executable code can reside in any


directory of your system, therefore Operating System provides a
specific search path that index the directories Operating System
should search for executable code.

The Path is set in the Environment Variable of My Computer


properties:
Keywords
PYTHON

The keywords are some predefined and reserved words in python that
have special meanings. The keyword cannot be used as an identifier,
function, and variable name. All the keywords in python are written in
lower case except

 True
 False
 None
There are 35 keywords in Python as of Now
Keywords
PYTHON

You can get a list of available keywords by using help() :


Keywords
PYTHON

you can use help() again by passing in the specific keyword that you
need more information about. You can do this, for example, with the
pass keyword:
Keywords in a
Way

Python also provides a keyword module for working with Python


keywords in a programmatic way. The keyword module in Python
provides two helpful members for dealing with keywords:

• kwlist provides a list of all the Python keywords for the version of
Python you’re running.

• iskeyword() provides a handy way to determine if a string is also


a keyword.
Keywords in a
Way
A name in Python program is called identifier.
It can be class name or name or name or
name.
a = 10
Identifiers are case sensitive. of course Python language is case sensitive
language.

So we know what a Python Identifier is. But can we name it anything?


Or do certain rules apply?
Well, we do have Some rules to follow when naming identifiers in Python:
IMPORTANT
IMPORTANT
myVar var_3 this_works

_9lives lives9

9lives
1 Alphabet Symbols (Either Upper case OR Lower case)

2 If Identifier is start with Underscore ( _ ) is considered poor programming style

3 Identifier should not start with Digits and are case sensitive.
KeyPoints
4 We cannot use reserved words as identifiers. Eg: def=10

5 There is no length limit for Python identifiers. But not recommended to use too
lengthy identifiers.
6 Dollar ($) Symbol is not allowed in Python.
IDENTIFIERS

Variable Func Class Module


Variable is a name that is used to refer to memory location. Python
variable is also known as an identifier and used to hold value.

In Python, we don't need to specify the type of variable because Python


is a dynamically typed language and smart enough to get variable
type.
type()
To check the type of variable

For ex

A = 10
type(A) Print()
id()
to get address of object

For ex

A = 10 id()
id(A)
print()
print in Python is the standard function used to print the output to the
console. Simply to print the value
One of the most basic and popular functions in Python – the print()
statement. We all might have started learning Python programming
with the evergreen example of printing ‘Hello World’. The Python
print() method is used to obtain output i.e. display anything on the
screen as well as to debug code. This function outputs the supplied
message or a value to the console
Suppose I Need to print this Statement in a single line with same Scenario

What should I do know


CONCLUSION

If you are thinking that


Then python interpreter to you be like
sep (Optional) – this specifies how objects should be
separated if multiple objects are passed. Default value: ‘ ‘

end (Optional) – specifies what is to be printed at last.


Default value: \n
Python Comment is a programmer’s tool. We use them to explain Comments
the code, and the interpreter ignores them.
You never know when a programmer may have to understand code
written by another and make changes to it.

Sometimes your brain will not remember what you have written and
it might forget it.

For these purposes, good code will hold comments in the right
places.
Run this Program and analyze
If you are thinking like that, this meme is perfectly match for you
1 Single Line

Multi Line 2

3 Doc strings
To Provide a Single Line comment we use (#)

If you want to provide multi line comments use (#) again in every
line there is no other way to declare multi line string
Multiline Python Comment

To have multiline python comment in your code, you must use a hash at
the beginning of every line of your comment in python.
Docstrings Python Comment

A docstring is a documentation string in Python. It is the first statement


in a module, function, class, or method in Python.
Don’t worry we will see function, methods, and classes later
It is just to aware
Escape sequences allow you to include special characters in strings. To
do this, simply add a backslash (\) before the character you want to
escape.

To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you


want to insert.
Operators
in Python
Python operator is a symbol that performs an operation on one or
more operands. An operand is a variable or a value on which we
perform the operation.

Operator is a symbol that performs certain operations.


Python provides the different types of operators
Arithmetic Relational Assignment
Operators Operators Operators

Logical Membership Identity


Operators Operators Operators
Floor Division
Addition (+)
(//)

Exponentiation
Subtraction(-) Division (/)
(**)

Multiplication
Modulus (%)
(*)
1 / operator always performs floating point arithmetic. Hence it will always returns float
value.
2 But Floor division (//) can perform both floating point and integral arithmetic. If
arguments are int type then result is int type. If atleast one argument is float type
then result is float type.
3 We can use +,* operators for str type also.
4 If we want to use + operator for str type then compulsory both arguments should
be str type only otherwise we will get error.
a
b
c
d
a
b
c
d
Less than (<) Equal to (==)

Greater than
Greater than(>) or equal to
(>=)

Less than or Not equal to


equal to (<=) (!=)
Relational operators are also called as Comparison operators
It is used to compare values
It either returns True or False according to condition.
a
b
c
d
a
b
c
d
Add and Subtract and Divide and
Assign (=)
Assign (+=) Assign (- =) Assign (/=)

Modulus Exponent Floor-Divide


Multiply and
and Assign and Assign and Assign
Assign (*=)
(%=) (**=) (//=)
1 and

or 2

3 not
Logical operator are typically used with Boolean (logical) values.
They allow a program to make a decision based on multiple condition
a
b
c
d
a
b
c
d
IN NOT
IN
In – membership operator
IN
• This checks if a value is a member of a sequence.

• In our next slide example, we see that the string ‘katrina’ does not
belong to the list cricketers. But the string ‘virat kohli’ belongs to it,
so it returns true.

• Also, the string ‘ali’ is a substring to the string ‘alia bhatt’. Therefore,
it returns true.
IN
Not In – Membership Operator
NOT IN
• This checks if a value is not a member of a sequence.

• In our next slide example, we see that the string ‘Katrina’ does not
belong to the list Cricketers. But the string ‘Virat Kohli’ belongs to it,
so it returns False.

• Also, the string ‘Ali’ is a substring to the string ‘Alia Bhatt’. Therefore,
it returns False.
NOT IN
a
b
c
d
a
b
c
d
Is
is not
Let us proceed towards identity Python Operator. is

These operators test if the two operands share an identity. We have two
identity operators- ‘is’ and ‘is not’.

If two operands have the same identity, it returns True. Otherwise, it


returns False.
Is
not
‘is not’

If two operands Doesn’t have the same identity, it returns True.


Otherwise, it returns False.
a
b
c
d
a
b
c
d
Programming Lab - 01

1. WAP to Add 2 Numbers.


2. WAP to Add 3 Numbers.
3. WAP to Sub 2 Numbers.
4. WAP to Multiply Two Numbers.
5. WAP to Divide Two Numbers.
6. WAP to Print Multiplication of a Table.
Data Types

Number Boolean String Bytes BytesArray List Tuple Dict Set

Integer
Frozen Set

Float

Complex
We can use int data type to represent whole numbers (integral values)
Eg: a=10
type(a) #int

In Python 3, there is effectively no limit to how long an integer value can INT
be. Of course, it is constrained by the amount of memory your system
has, as are all things, but beyond that an integer can be as long as you
need it to be:
We can use float data type to represent floating point values (decimal
values)
Eg: f=1.234
type(f) float
We can also represent floating point values by using exponential form
(scientific notation)
Eg: f=1.2e3
print(f) 1200.0
The main advantage of exponential form is we can represent big values
in less memory.
A complex number is of the form

We can use complex type generally in scientific Applications and


electrical engineering Applications.
We can use this data type to represent boolean values.
The only allowed values for this data type are:
True and False
Internally Python represents True as 1 and False as 0
b=True
type(b) =>bool
True False
Strings in
Python
S T R I N G

Many of us who are familiar with programming languages like C,


C++ etc. will have an answer like “String is a collection or array of
characters.”

Well in Python also, we say the same definition for String data type.
String is array of sequenced characters and is written inside single
quotes, double quotes or triple quotes. Also, Python doesn’t have
character data type, so when we write ‘a’, it is taken as a string with
length 1.
S T R I N G

str represents String data type.


A String is a sequence of characters enclosed within single quotes or
double quotes.

s1= ‘World'
s1= “World“

In Python , we can represent char values also by using str type and
explicitly char type is not available.
S T R I N G

By using single quotes or double quotes we cannot represent multi line


string literals.
S1 = “ World
Class ”
For this requirement we should go for triple single quotes(''') or triple
double quotes( “ “ “ )

We can also use triple quotes to use single quote or double quote in
our String.
S T R I N G

slice means a piece [ ] operator is called slice operator , which can be


used to retrieve parts of String.
The index can be either +ve or -ve.
+ve index means forward direction from Left to Right
-ve index means backward direction from Right to Left

It allows programmers to extract information from a string of data.


The slicing is not just restricted to strings but can be applied to tuples
and lists as well.
S T R I N G
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1

H E L L O W O R L D

0 1 2 3 4 5 6 7 8 9
How to get substring in Python?

Str [ start : stop : step ]

Start index Stop index


String Step Size
of substring of substring
Variable Default 1
(included) (excluded)
STRING THE
PREDICT SLICING
OUTPUT

🤔 🤔
PREDICT THE OUTPUT

🤔 🤔
PREDICT THE OUTPUT

🤔 🤔
We can apply the following mathematical operators for Strings.

1. + operator for concatenation

2. * operator for repetition

print(“Vicky"+“Katrina") #VickyKatrina

print(“Kat"*3) #KatKatKat
Note:

1. To use + operator for Strings, compulsory both arguments should


be str type IMPORTANT

2. To use * operator for Strings, compulsory one argument should be


str and other argument should be int
a
b
c
d
a
b
c
d
% OLD STYLE
How to format
a String in {} .FORMAT

Python
f’ F STRING
How to format
Formatting a string is something you'll do all the time when you're
coding in Python.
a String in
Python
Sometimes, you may want to print variables along with a string. You
can either use commas, or use string formatters for the same.

Name = “Alia”
str = “ Hello” , Name, “How are you. “
% OLD STYLE
1. Format a String the Old Way: print ‘Hello %s ’ % name

This approach was more often used in Python2, when the language
was still young and evolving. It's a technique that is easy to
understand for veteran coders who come from a C programming
background.
%d – for integers
%s – for strings
%f – for floating-point numbers
% OLD STYLE
Example to Understand
{} .FORMAT
2. Format a String using Format: ‘’.format()

This is a technique that many Python programmers consider a breath


of fresh air, since it makes things easier for you.

It was introduced in early Python3. Essentially, the new syntax


removed the ‘%’ symbols and instead provided .format() as a string
method.
{} .FORMAT
2. Format a String using Format: ‘’.format()

Python Format()
Function

“ { } ”.format(value)
Example to Understand
f’ F STRING
3. Format a String using F Strings
Also short for format string, f strings are the most recent technique
that Python3 now supports so they're being adopted rapidly.

F strings addresses the verbosity(more words) of the .format()


technique and provide a short way to do the same by adding the letter
f as a prefix to the string.
it also happens to be simpler for students to learn, and easier to adopt
if you're still new to coding.
f’ F STRING

Example to Understand
String

Everything in Python is an object. A string is an object too. Python


provides us with various methods to call on the string object.

Let’s look at each one of them.

String Functions in Python


LEN() –

We can use len() function to find the number of characters present in


the string.

LEN()
LEN() –

a
b
c
d
Counting

We can find the number of occurrences of substring present in the


given string by using count() method.

COUNT()
a
b
c
d
a
b
c
d
Python
replace() is an inbuilt function in the Python programming language String
that returns a copy of the string where all occurrences of a substring
Replace
are replaced with another substring.

String.replace(old,new,count)
Syntax :
Optional
string.replace(old, new, count)
old – old substring you want to replace.
new – new substring which would replace the old substring.
count – the number of times you want to replace the old substring with
the new substring. (Optional )
Python String
• If count is not specified then all the occurrences of the old
substring are replaced with the new substring. Replace
• This method returns the copy of the string i.e. it does not change
the original string.
Example to Understand
We can split the given string according to specified seperator by
using split() method.
“Hello World”
l=s.split(seperator)
String split()
The default seperator is space.
The return type of split() method is List
[“Hello”,”World”]
String = “I am a string.”

split()

[ “I” , ”am” , ”a” , ”string.” ]


Example to Understand
We can join a group of strings(list or tuple) by the given seperator.
S = seperator.join(group of strings)

[ “Hello” , “World” ]

Join()

“Hello World”
a
b
c
d
a
b
c
d
a
b
c
d
a
b
c
d
a
b
c
d
a
b
c
d
a
b
c
d
a
b
c
d
a
b
c
d
a
b
c
d
KeyPoints

• In Python the following 5 data types are considered as Fundamental 1 int

• In Python , we can represent char values also by using str type and 2 float
explicitly char type is not available.
3 complex

• Long Data Type is available in Python2 but not in Python3. 4 bool

5 str
AC T i Vi T Y Ti M E

Practice ! Practice ! Practice

Practice as much as you can as Strings are the most important topic in
any programming language and also for the Interview Room

We can do String Related Programming Questions Later when we are


familiar with programming in python ( Control Flow i.e. loops if
statements etc )
Indentation refers to the whitespaces (usually 4 spaces or a single tab)
that signify the beginning of a suite (block) of code. All statements Indentation
indented at the same level belong to the same suite.

In other languages, a block of code is written inside curly braces


( { } ).
Indentation
Python has made the syntax a bit simpler by removing these curly
braces from the block of your code. You do not need to type anything
to mark the beginning and the end of a block.

Instead in Python, we use indentation along with colon ( : ) for that


purpose. The colon ( : ) introduces a new suite(block) of code
Example to Understand
• In Python programming, flow control is the order in which statements
or blocks of code are executed based on a condition.
Flow Control
• Control flow is the order in which the statements execute. For example,
the program’s flow is usually from top to bottom(Sequential flow), but
what if we want a particular block of code to only be executed when
it fulfills a specific condition or wants to run a block of the code a
specified number of times? These statements will ensure a smooth and
intentional flow of a program.
There are three types of control statements:
Flow Control
FLOW CONTROL

Decision Statements Transfer Statements Iterative Statements

1. if 1. break
2. if-else 2. continue 1. for
3. if-elif-else 3. pass 2. while
4. Nested if-else
In Python, condition statements act depending on whether a given
condition is true or false. You can execute different blocks of codes
depending on the outcome of a condition. Condition statements always
evaluate to either True or False.
Sometimes, in a program, we may want to make a decision based on a
condition. We know that an expression’s value can be True or False. We
may want to do something only when a certain condition is true.

For example, assume variables a and b. If a is greater, then we want to


print “a is greater”. Otherwise, we want to print “b is greater”.

For this, we use an if-statement


01 02 03 04

If If else If - elif -
Nested if
statement statement else
statement
statement
01
if statement is the most simple form of decision-making statement. It
takes an expression and checks if the expression evaluates to True then If
the block of code in if statement will be executed. statement

If the expression evaluates to False, then the block of code is skipped.


SYNTAX

False

True
AC T i Vi T Y Ti M E
AC T i Vi T Y Ti M E
02
From the name itself, we get the clue that the if-else statement checks the
If else
expression and executes the if block when the expression is True statement
otherwise it will execute the else block of code. The else block should be
right after if block and it is executed when the expression is False.
SYNTAX

True

False
AC T i Vi T Y Ti M E
AC T i Vi T Y Ti M E

WAP to find Voting eligibility of a person.


CONCLUSION

If you are thinking that the output is you are eligible to vote then python
interpreter to you be like
CONCLUSION

You know why because of indentation error remember we have just


cover the small topic but.,
It will give you errors which you can’t able to find especially if you are
beginner
WAP to find Voting eligibility of a person.
Programming Lab - 02

7. Write a program to find voting eligibility by user input

8. Write a program to find maximum between two numbers.

9. WAP to find whether a number is even or odd


03
if statement is the most simple form of decision-making statement. It
takes an expression and checks if the expression evaluates to True then If - elif -
the block of code in if statement will be executed. else
statement
If the expression evaluates to False, then the block of code is skipped.
SYNTAX
AC T i Vi T Y Ti M E
Programming Lab – 03

10. Write a program to find maximum between three numbers.

11. Write a program to check whether a number is negative,


positive or zero.
04
In Python, the nested if-else statement is an if statement inside another
if-else statement. It is allowed in Python to put any number of if
Nested if
statements in another if statement.
statement

Indentation is the only way to differentiate the level of nesting. The


nested if-else is useful when we want to make a series of decisions.
SYNTAX
04

Nested if
statement
Programming Lab - 04

12. WAP to Make Calculator

13. Write a to calculate profit or loss.

14. WAP To Make a Marksheet of a student taking 4 subjects as


input and display the total, percent & its result
When you want some statements to execute a hundred times, you
don’t repeat them 100 times.

Think of when you want to print numbers 1 to 99. Or that you want
to say Hello to 99 friends.

In such a case, you can use loops or iterative statements in python.


Loops are one of the most powerful and basic concepts in
programming. A loop can contain a set of statements that keeps on
executing until a specific condition is reached.

Today, we are going to learn about the loops that are available in
Python.
1. For Loop
2. While Loop
3. Nested Loop
LOOPS

FOR WHILE NESTED


LOOP LOOP LOOP
Python for loop can iterate over a sequence of items. The structure FOR
of a for loop in Python is different than that in C++ or Java. LOOP

That is, for(int i=0;i<n;i++) won’t work here. In Python, we use the
keyword.
Lets see a Python for loop Example
SYNTAX
FOR
LOOP
The range() function Iterating on indices of
1 with For Loop 3 a list or a similar construct

Iterating on lists or The else statement


2 similar constructs 4 for for-loop
When using for loops in Python, the range() function is pretty useful
to specify the number of times the loop is executed. It yields a
sequence of numbers within a specified range.

1. The first argument is the starting value. It is zero by default.


2. The second argument is the ending value of the range.
3. The third argument is the number of steps to take after each
yield.
You can use the for loop to iterate over the range of objects.
FOR
LOOP
Similarly, we can iterate the same way in tuples, lists, sets, and
FOR
strings. LOOP
Iterating on lists or
2
similar constructs

You aren’t bound to use the range() function, though. You can use the
loop to iterate on a list or a similar construct.
Iterating on indices of
3
a list or a similar construct

The len() function returns the length of the list. When you apply the
range() function on that, it returns the indices of the list on a range
object. You can iterate on that.
The else statement
4
for for-loop

A for-loop may also have an else statement after it.

When the loop is exhausted, the block under the else statement
executes.
The else statement
4
for for-loop

It doesn’t execute if you break out of the loop or if an exception is


raised. Just run the program and observe the Difference. These basic
internal knowledge will prepare you to learn python very easily
AC T i Vi T Y Ti M E

Using For Loop

Write a program to print counting from 1 to 10.

Write a program to print counting from 10 to 1 (Reverse order).


a
b
c
d
a
b
c
d
A while loop in python iterates till its condition becomes False. In
other words, it executes the statements under itself while the WHILE
condition it takes is True LOOP
When the program control reaches the while loop, the condition is
checked. If the condition is true, the block of code under it is
executed.

Remember to indent all statements under the loop equally. After


that, the condition is checked again.
This continues until the condition becomes false.
SYNTAX
AC T i Vi T Y Ti M E

Using While Loop

Write a program to print counting from 1 to 10.

Write a program to print counting from 10 to 1 (Reverse order).


While Loops

The else statement


1 An Infinite Loop for While Loop
2
Be careful while using a while loop. Because if you forget to
increment the counter variable in python, or write logic, the condition
may never become false.

In such a case, the loop will run infinitely , and the conditions after the
loop will starve. To stop execution, press Ctrl+C.

However, an infinite loop may actually be useful.


This is important we have to run the condition explicitly as per our
own needs if don’t do that there may be a chance of infinite loop
AC T i Vi T Y Ti M E

Write a Simple Program to Ask name from user and greet them
With the message that you want to add more name

If user press Y then again same process


If user press N then Stop the execution
AC T i Vi T Y Ti M E

Observe Carefully
A while loop may have an else statement after it. When the condition
becomes false, the block under the else statement is executed.

However, it doesn’t execute if you break out of the loop or if an


exception is raised.
It doesn’t execute if you break out of the loop or if an exception is
raised. Just run the program and observe the Difference. These basic
internal knowledge will prepare you to learn python very easily
a
b
c
d
a
b
c
d
After Doing Previous 2 Practicals
As a Learner, After learning Loops Concept We always have a
question which one to prefer firstly, Here is your Answer

FOR WHILE
LOOP LOOP
An unknown number of times:
For example, Ask the user to guess the lucky number. You don’t know FOR WHILE
how many attempts the user will need to guess correctly. It can be 1, LOOP LOOP

20, or maybe indefinite. In such cases, use a while loop.

Fixed number of times:


Print the multiplication table of 2. In this case, you know how many
iterations you need. Here you need 10 iterations. In such a case use
for loop.
Nested for loop is a for loop inside another for a loop.

A nested loop has one loop inside of another. It is mainly used with
two-dimensional arrays. For example, printing numbers or star
patterns. Here outer loop is nothing but a row, and the inner loop is
columns.
SYNTAX
AC T i Vi T Y Ti M E

Example to Understand
AC T i Vi T Y Ti M E

Write a program to print Pattern like this


All Right We have completed the nested loops it is very important
especially in pattern programs so practice as much as you can
We will do this nesting concept through out in our programming IMPORTANT

Note: If the break statement is used inside a nested loop (loop inside
another loop), it will terminate the innermost loop.
Python allows us to control the flow of the execution of the program in
a certain manner. For this we use the continue, break and pass
keywords.

For this, we have three keywords in Python-


Transfer
Python
Statements

BREAK CONTINUE PASS


BREAK

The break statement inside a loop is used to exit out of the loop.
Sometimes in a program, we need to exit the loop when a certain
condition is fulfilled.

When you put a break statement in the body of a loop, the loop
stops executing, and control shifts to the first statement outside it.

You can put it in a for or while loop.


BREAK

It is used to terminate the loop, and program control resumes at the


next statement following the loop.
CONTROL FLOW OF BREAK STATEMENT

Terminate the Loop


Statement 3 & 4 will
not execute
PROGRAM TO UNDERSTAND BREAK

Run the program and observe


CONTINUE

The continue statement skip the current iteration and move to the next
iteration. In Python, when the continue statement is encountered inside
the loop, it skips all the statements below it and immediately jumps to
the next iteration.

In simple words, the continue statement is used inside loops. Whenever


the continue statement is encountered inside a loop, control directly
jumps to the start of the loop for the next iteration, skipping the rest
of the code present inside the loop’s body for the current iteration.
CONTINUE

In some situations, it is helpful to skip executing some statement inside


a loop’s body if a particular condition occurs and directly move to the
next iteration.
CONTORL FLOW OF CONTINUE STMT

Moved to the
next iteration
Skipped for
particular
iteration
PROGRAM TO UNDERSTAND CONTINUE

Run the program and observe


PASS

The pass is the keyword In Python, which won’t do anything.


Sometimes there is a situation in programming where we need to
define a syntactically empty block. We can define that block with the
pass keyword.

A pass statement is a Python null statement. When the interpreter


finds a pass statement in the program, it returns no operation. Nothing
happens when the pass statement is executed.
PASS

Sometimes We don’t know the full implementation of the program just


we need to declare that so pass is used to provide null body and
there is no syntax error
SUMMARY

BREAK

CONTINUE

PASS
SUMMARY
BREAK

What is the output ?


Stands for "American Standard Code for Information Interchange."
ASCII is a character encoding that uses numeric codes to
represent characters. These include upper and lowercase English
letters, numbers, and punctuation symbols.

It is a code for representing 128 English characters as numbers, with


each letter assigned a number from 0 to 127. For example, the ASCII
code for uppercase M is 77.
AC T i Vi T Y Ti M E

1. Search on Google & Explore the Table of Ascii Characters

2. WAP to print Ascii code of any Character.

3. WAP to Convert a Character Lowercase to Uppercase and vice


versa
Programming Lab - 05

15. WAP to print EVEN No Up to = 50

16. WAP to print EVEN No to Nth Number

17. WAP to print ODD No to Nth Number

18. WAP to print EVEN and Odd to Nth Number

19. WAP to print EVEN and Odd to Nth Number With their Sum
Python’s if-else statements are very easy to write and read. But they
come with a downside. That is, if you want to print something based
on some condition, you need 4 lines to do that.

That’s an awful lot of lines for such a simple operation. What’s the
solution, you ask? Ternary operators in Python!
The ternary operator in Python is nothing but a of the
if-else statement. It provides a way to write conditional statements in
a single line, replacing the multi-line if-else syntax.

Syntax of Python ternary operator


Python ternary operator works with three operands:

This is a boolean condition that evaluates


to either true or false.

The value returned by the ternary operator if the


conditional_expression evaluates to True.

3. false_value: The value returned by the ternary operator if the


conditional_expression evaluates to False.
Example
Programming Lab - 06

By Using Ternary Operator

20. WAP to print Whether a Number is Even or Odd

21. WAP to find Largest No B/w Two Numbers


Programming Lab - 07

22. WAP to Swap the 2 Numbers

23. WAP to display a series that is divisible by 7

24. WAP to Calculate the income tax as per the given Slab
TYPE CASTING

Type Casting is the method to convert the variable data type into a
certain data type in order to the operation required to be performed
Python
by users. Type
Casting
We can convert one type value to another type.

1. int()
2. float()
3. bool()
4. str()
TYPE CASTING

Python
There can be two types of Type Casting in Python –
Type
Casting
Implicit Type Casting

Explicit Type Casting


TYPE CASTING

Implicit
ImplicitType
TypeConversion
Casting

In this, methods, Python converts data type into another data type
automatically. In this process, users don’t have to involve in this process.
Implicit Type Casting
TYPE CASTING

Explicit Type
Explicit Type Casting
Casting

In this method, Python need user involvement to convert the variable


data type into certain data type in order to the operation required.
TYPE CASTING

Mainly in type casting can be done with these data type function:

Int() - Int() function take float or string as an argument and return int
type object.

float() - float() function take int or string as an argument and return


float type object.

str() - str() function take float or int as an argument and return string
type object.
EXPLICIT TYPE CASTING
EXPLICIT TYPE CASTING
EXPLICIT TYPE CASTING
TYPE CASTING

🧐
a
b
c
d
TYPE CASTING

a
b
c
d
TYPE CASTING

a
b
c
d
TYPE CASTING

a
b
c
d
TYPE CASTING

🧐 🧐
TYPE CASTING

a
b
c
d
Programming Lab - 08

25. WAP to Print Fibonacci Series

26. WAP to print whether a number is prime or not.

27. WAP to print factorial of a given no.


Programming Lab - 09

28. WAP to print Prime Number 1 to 100.

29. WAP to print Prime Number 1 to Nth Number

30. WAP to print Prime Number 1 to Nth Number with their sum.
Programming Lab - 10

31. WAP to reverse a number

32. WAP to check whether a Number is Palindrome or not.


MUTABLE IMMUTABLE
All Fundamental Data types are immutable. I.e once we creates an
object , we cannot perform any changes in that object. If we are trying
to change then with those changes a new object will be created. This
non-changeable behaviour is called immutability
In Python if a new object is required, then PVM wont create object immediately. First it
will check is any object available with the required content or not. If available then
existing object will be reused. If it is not available then only a new object will be created.
The advantage of this approach is memory utilization and performance will be improved.

But the problem in this approach is , several references pointing to the same object , by
using one reference if we are allowed to change the content in the existing object then the
remaining references will be effected. To prevent this immutability concept is required.
According to this once creates an object we are not allowed to change content. If we are
trying to change with those changes a new object will be created.
PROGRAM TO EXPLAIN IMMUTABILITY

Run and Analyze the program


PROGRAM TO EXPLAIN IMMUTABILITY

We Can’t Change this Python Object as it is Immutable


Suppose if a = 10 , b = 10 then both are sharing the same object
a

10 Python Object

b
CONCLUSION

Now you might be thinking that we can change the value of a and b
CONCLUSION

When we are trying to change the value of a and b then


A new object will be created and the variable a as in previous example
Is pointing towards that object

b 10 Python Object

New Python
a 20 Object Created
PATTERNS

PATTERN PROGRAMS
Programming Lab - 11

WAP to print Star Pattern

*
* *
* * * 33
* * * *
* * * * *
* * * * * *
Programming Lab - 12

1 1 1
2 2 1 2 2 3
3 3 3 34 1 2 3 35 4 5 6 36
4 4 4 4 1 2 3 4 7 8 9 10
5 5 5 5 5 1 2 3 4 5 11 12 13 14 15

5 5
4 4 5 4
3 3 3 37 5 4 3 38

2 2 2 2 5 4 3 2
1 1 1 1 1 5 4 3 2 1
Programming Lab - 13

WAP to print Star Pattern

* * * * * *
* * * * *
* * * * 39
* * *
* *
*
Programming Lab - 14

5 5 5 5 5 5 4 3 2 1 1 2 3 4 5
4 4 4 4 5 4 3 2 6 7 8 9
3 3 3 40 5 4 3 41 10 11 12 42
2 2 5 4 13 14
1 5 15

1 2 3 4 5 1 1 1 1 1
1 2 3 4 2 2 2 2
1 2 3 43 3 3 3 44
1 2 4 4
1 5
Programming Lab - 15

WAP to print Star Pattern

45
Programming Lab - 16

46 47 48

49 50
Programming Lab - 17

WAP to print Star Pattern

51
Programming Lab - 18

52 53 54

55 56
Programming Lab - 19

WAP to print Star Pattern


57
Programming Lab - 20

WAP to print Star Pattern


58
Programming Lab - 21

WAP to print Star Pattern


59
Programming Lab - 22

60. WAP Sum of every number in a Digit


for ex = 12345 => 1+2+3+4+5 = 15 Output

61. WAP Sum of every Odd number in a Digit


for ex = 12345 => 1+3+5 = 9 Output

62. WAP Sum of every Even number in a Digit


for ex = 12345 => 2+4 = 6 Output
BYTES

bytes data type represents a group of byte numbers just like an array
i.e. it is immutable
Python Bytes()
BYTES

Conclusion 1:
The only allowed values for byte data type are 0 to 256. By mistake if Python Bytes()
we are trying to provide any other values then we will get value error.

Conclusion 2:
Once we creates bytes data type value, we cannot change its values ,
otherwise we will get TypeError
BYTES ARRAY

bytearray is exactly same as bytes data type except that its elements
can be modified i.e. it is mutable
BytesArray()
BE ATTENTIVE

LEVEL UP
LISTS

IMPORTANT

Python Lists
LISTS

Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections Python Lists
of data, the other 3 are Tuple, Set, and Dictionary, all with different
qualities and usage.

Lists are created using square brackets:


LISTS

If we want to represent a group of values as a single entity where


insertion order required to preserve and duplicates are allowed then we
should go for list data type. Python Lists
1. insertion order is preserved
2. heterogeneous objects are allowed
3. duplicates are allowed
4. Growable in nature
5. values should be enclosed within square brackets.
LISTS

[]

EMPTY
LIST
CREATION OF LISTS

1. We can create empty list object as follows...


CREATION OF LISTS

2. If we know elements already then we can create list as follows


CREATION OF LISTS

3. We can create list with list() Function It is function which can


typecast compatible objects to list type
CREATION OF LISTS

4. With dynamic input:


By using eval() Function
CREATION OF LISTS

5. With split() Function


ACCESSING ELEMENTS OF LISTS

We can access elements of the list either by using index or by using


slice operator(:)

1. By using index:

2. By using slice operator:


ACCESSING ELEMENTS OF LISTS

L = [ 140 , “HELLO” , 15.25 , True , 0


]

(-) -5 -4 -3 -2 -1

140 “HELLO 15.25 True 0



(+) 0 1 2 3 4
ACCESSING ELEMENTS OF LISTS

1. By using index:

List follows zero based index. ie index of first element is zero.


List supports both +ve and -ve indexes.

-ve index meant for Right to Left

+ve index meant for Left to Right


ACCESSING ELEMENTS OF LISTS

-4 -3 -2 -1

List = 10 20 30 40

0 1 2 3
ACCESSING ELEMENTS OF LISTS

2. By using slice operator:


[start:stop:step]
The list is an iterable data-type and hence we can slice the list. The list is
the same as an array in another programming language. By using List Slicing
slicing we can traverse through the whole list, we can reverse it and
print it from a specific start index to ending index.

Slicing concept you have already learned in Strings It is same that of


list
ACCESSING ELEMENTS OF LISTS

Slicing of List in Python?

list [ start : stop : step ]

Start index Stop index


List Step Size
of List of List
Variable Default 1
(included) (excluded)
AC T i Vi T Y Ti M E
AC T i Vi T Y Ti M E

1. WAP to Reverse a List using Slicing


TRAVERSING ELEMENTS OF LISTS

The sequential access of each element in the list is called traversal.

1. By using while loop:

2. By using for loop:


TRAVERSING ELEMENTS OF LISTS

1. By using while loop: Traversing a


List
using While Loop
TRAVERSING ELEMENTS OF LISTS

Traversing a
2. By using for loop: List
using For Loop
DISPLAY ONLY EVEN NUMBERS
AC T i Vi T Y Ti M E

1. WAP to display elements in Lists by index wise


negative and positive index
BUILT IN FUNCTIONS FOR LIST
LEN () & COUNT()

len() count()
Python List Python List
INDEX()

Note: If the specified element not present in the list then we will get index()
ValueError. Hence before index() method we have to check whether
Python List
item present in the list or not by using in operator.
BUILT IN FUNCTIONS FOR LIST
We can use append() function to add item at the end of the list.
Append
()
List = 10 20 30 40

RUN
To add all elements to list upto 100 which are divisible by 10
To insert item at specified index position insert()
Python List

If the specified index is greater than max index then element will be
inserted at last position. If the specified index is smaller than min
index then element will be inserted at first position.
insert()
List = 10 20 30 40
Python List

List = 10 20 500 30 40

RUN
To add all items of one list to another list extend()
l1.extend(l2)
all items present in l2 will be added to l1 Python List
We can use this function to remove specified item from the list. If the remove()
item present multiple times then only first occurrence will be removed.
Python List
If the specified item not present in list then we will get ValueError remove()

Python List

Note: Hence before using remove() method first we have to check


specified element present in the list or not by using IN operator.
POP()

It removes and returns the last element of the list.


pop()
This is only function which manipulates list and returns some element.
Python List
POP()

List = 10 20 30 40 POP

List = 10 20 30 POP

List = 10 20
POP()

Note: pop()

1. If the list is empty then pop() function raises IndexError Python List
2. pop() is the only function which manipulates the list and returns
some value
3. In general we can use pop() function to remove last element
of the list. But we can use to remove elements based on index.
POP()

n.pop(index)===>To remove and return element present at specified


index.
n.pop()==>To remove and return last element of the list
SUMMARY

List objects are dynamic. i.e based on our requirement we can


increase and decrease the size.

append(),insert() ,extend() for increasing the size/growable


nature

remove(), pop() for decreasing the size /shrinking nature


BUILT IN FUNCTIONS FOR LIST
REVERSE()

We can use to reverse() order of elements of list. reverse()

Python List
REVERSE()

Revers
List = 10 20 30 40 e

List =
SORT()

In list by default insertion order is preserved. If want to sort the


sort()
elements of list according to default natural sorting order then we
should go for sort() method.
Python List

For numbers default natural sorting order is Ascending Order


For Strings default natural sorting order is Alphabetical Order
SORT()

To sort in reverse of default natural sorting order:


We can sort according to reverse of default natural sorting order by
using reverse=True argument.
SORT()

n= 40 10 20 30 n.sort()

n=
CLEAR()

We can use clear() function to remove all elements of List. clear()

Python List
APPEND() INSERT()
REMOVE() POP()
Aliasing AND Cloning of List

Aliasing of List Cloning of List


Aliasing of List

PYTHON
The process of giving another reference variable to the existing list
is called Aliasing.
Aliasing List
Aliasing of List

10 20 30 40
x PYTHON
Y
Aliasing List

The problem in this approach is by using one reference variable if we


are changing content, then those changes will be reflected to the
other reference variable.
Aliasing of List

10 20777 30 40
x
Y

To overcome this problem we should go for cloning.


Cloning of List

Python
The process of creating exactly duplicate independent object is called
cloning. Copying and
Cloning [ ]
We can implement cloning by

 using slice operator

 using copy() function


Cloning of List

1. Cloning by using slice operator

Python
Copying and
Cloning [ ]
Cloning of List

10 20 30 40
x

10 20 777 30 40
Y
Cloning of List

2. Cloning by using copy() function


= COPY()

=
Q. Difference between = operator and copy() function
Copy

 = operator meant for aliasing

 copy() function meant for cloning


MATHMATICAL OPERATORS
FOR LIST

Mathematical operators for List Objects

We can use + and * operators for List objects.

1. Concatenation operator(+)

2. Repetition Operator(*)
MATHMATICAL OPERATORS
FOR LIST

1. Concatenation operator(+)

We can use + to concatenate 2 lists into a single list

Note: To use + operator compulsory both arguments should be list


objects , otherwise we will get TypeError .
MATHMATICAL OPERATORS
FOR LIST

2. Repetition Operator(*)
We can use repetition operator * to repeat elements of list specified
number of times
Comparing Lists

We can use comparison operators for List objects.


Comparing Lists

Note: Whenever we are using comparison operators(==,!=) for List KeyPoints


objects then the following should be considered

1. The number of elements


2. The order of elements
3. The content of elements (case sensitive)

Note: When ever we are using relational operators(<,<=,>,>=)


between List objects , only first element comparison will be
performed.
MEMBERSHIP OPERATORS
FOR LIST

• We have already learned Membership Operator in Operators Python Membership


Concept We are here just to aware the working of these operator Operators
with python Lists
NOT
IN
• We can check whether element is a member of the list or not by IN
using membership operators.

in operator

not in operator
MEMBERSHIP OPERATORS
FOR LIST

Example Python Membership


Operators

NOT
IN
IN
AC T i Vi T Y Ti M E

On the basis of this Find is present in the list or not.


Nested LIST

Nested
• Lists are useful data structures commonly used in Python
programming. A nested list is a list of lists, or any list that has
Lists
another list as an element (a sublist). PYTHON

• Sometimes we can take one list inside another list. Such type of lists
are called nested lists.
Nested LIST

list 1 2 3

List[2] ‘a’ 1

An Example of Nested List


Nested LIST

Run and Analyze the Example Nested


Lists
PYTHON
List Comprehensions

It is very easy and compact way of creating list objects from any
iterable objects ( like list, tuple, dictionary, range etc ) based on some
condition.

SYNTAX

List = [expression for item in list if condition]


AC T i Vi T Y Ti M E

1. Simple list to store num from 1 to 10

2. Simple list to store even numbers from 1 to 100


Using List
3. Simple list to store square of num from 1 to 10 Comprehension

4. Simple list to find max among 2 numbers

5. Simple list to find max among 3 numbers


Programming Lab - 23

63. WAP to Input values through user in list and print their sum.

64. WAP to print Odd & Even Numbers to in a list to Nth Number.
Programming Lab - 24

65. WAP to Input values through user in list and print it.

66. WAP to Input values through user in list and Update it.

67. WAP to Input values through user in list and Insert value in it.

68. WAP to Input values through user in list and perform search
operation.
Programming Lab - 25

69. WAP to Input values through user in list and Delete an Element
by Index.

70. WAP to Input values through user in list and Delete an Element
by Value.
TUPLES

IMPORTANT

Python Tuples
TUPLES

Python tuples are used to store an ordered sequence of values.


Tuples are immutable, this means that the values in a tuple cannot be
changed once the tuple is defined. The values in a tuple are comma-
separated and they are surrounded by parentheses.
TUPLES

, ,
TUPLES

1. Tuple is exactly same as List except that it is immutable. i.e once


we creates Tuple object , we cannot perform any changes in
that object.
Hence Tuple is Read Only version of List.

2. If our data is fixed and never changes then we should go for Tuple

3. Insertion Order is preserved

4. Duplicates are allowed


TUPLES

5. Heterogeneous objects are allowed.

6. We can preserve insertion order and we can differentiate


duplicate objects by using index. Hence index will play very
important role in Tuple also. Tuple support both +ve and -ve
index. +ve index means forward direction(from left to right) and -
ve index means backward direction(from right to left)

7. We can represent Tuple elements within Parenthesis and with


comma seperator. Parenethesis are optional but recommend to use
CREATION OF TUPLES

1. We can create empty Tuple object as follows...


CREATION OF TUPLES

2. If we know elements already then we can create tuple as follows


CREATION OF TUPLES

3. We can create list with tuple() Function It is function which can


typecast compatible objects to tuple type
CREATION OF TUPLES

a
b
c
d
CREATION OF TUPLES

a
b
c
d
CONCLUSION

Most of you are saying it’s a tuple 😂 But my friend it’s not a Tuple
CONCLUSION

Note: We have to take special care about single valued tuple,


compulsary the value should ends with comma , otherwise it is not
treated as tuple. It is treated as int
Which of the following are valid TUPLES

Write down the answers in you notebook then run the one by one and
analyze as per your answers
Accessing Elements of TUPLES

We can access elements of the tuples either by using index or by using


slice operator(:) Python Tuples

1. By using index:

2. By using slice operator:


Accessing Elements of TUPLES

1. By using index:

Tuple follows zero based index. ie index of first element is zero. Python Tuples
Tuple supports both +ve and -ve indexes.

-ve index meant for Right to Left

+ve index meant for Left to Right


Accessing Elements of TUPLES

Tuple = ( ‘a’ , ‘e’ , ‘i’ , ‘o’ , ‘u’ )


0 1 2 3 4

Tuple[0]

Tuple[1]
Tuple[2]

Tuple[3]

Tuple[4]
Accessing Elements of TUPLES

2. By using slice operator:

We have already covered this concept in Lists it performs same


functionality as that of list if you can’t remember then refer
Slide No 317 again
AC T i Vi T Y Ti M E
AC T i Vi T Y Ti M E

1. WAP to Reverse a Tuple using Slicing


“ index out of range “
TUPLES

In the previous slides we have seen how to use positive and negative
indexes to access the items in a tuple.
Let’s see what happens if we use indexes that fall outside the boundaries
of the tuple.

For this tuple the maximum valid positive index is 4 and it refers to the
last item. Here is what happens if we use the index 5…
“ index out of range “
TUPLES

Something similar also applies to negative indexes…

The Python interpreter raises an “tuple index out of range” exception


when trying to access an item in the tuple by using a positive index
greater than the size of the tuple minus one. The same error also occurs
when trying to access an item by using a negative index lower than the
size of the tuple.
Traversing the Elements of TUPLES

The sequential access of each element in the Tuple is called traversal.

1. By using while loop:

2. By using for loop:

It is exactly same as the lists Refer Slide No 321


Traversing the Elements of TUPLES

Traversing a
1. By using while loop:
Tuple
using While Loop
Traversing the Elements of TUPLES

Traversing a
2. By using for loop:
Tuple
using For Loop
AC T i Vi T Y Ti M E

What is the Output ?


CONCLUSION

If you are coming from C or Java Background then you must predicted
something but the answer is Syntax error
TUPLE

A tuple is immutable, this means that once created you cannot add more
elements to a tuple i.e, we cannot change its content.

When you do that you get back a TypeError exception that says that an
object of type tuple does not support item assignment. IMMUTABLE

Hence tuple objects are immutable.


TUPLE

IMMUTABLE
MATHMATICAL OPERATORS
FOR TUPLES

Mathematical operators for Tuple Objects

We can use + and * operators for Tuple objects.

1. Concatenation operator(+)

2. Repetition Operator(*)
MATHMATICAL OPERATORS
FOR TUPLES

1. Concatenation operator(+)

We can use + to concatenate 2 tuples into a single tuple

Note: To use + operator compulsory both arguments should be tuple


objects , otherwise we will get TypeError .
MATHMATICAL OPERATORS
FOR TUPLES

2. Repetition Operator(*)

We can use repetition operator * to repeat elements of tuples


specified number of times
Deleting a Tuple

Tuples are immutable objects so we cannot change or modify tuples.

Hence now we conclude that we cannot delete an element from the


tuple.

But we can delete the whole tuple.


BUILT IN FUNCTIONS FOR TUPLES
LEN()

To return number of elements present in the tuple

LEN()
COUNT()

To return number of occurrences of given element in the tuple

COUNT()
INDEX()

Returns index of first occurrence of the given element.


If the specified element is not available then we will get ValueError.

INDEX ()
SORTED()

To sort elements based on default natural sorting order

We can sort according to reverse of default natural sorting order as


follows
MIN() & MAX()

These functions return min and max values


Min ()
And
Max ()
PYTHON
PACKING AND UNPACKING OF TUPLES
TUPLE PACKING

TUPLE PACKING

We can create a tuple by packing a group of variables.

Here a,b,c,d are packed into a tuple t. This is nothing but tuple packing.
TUPLE UNPACKING

TUPLE UNPACKING

Tuple unpacking is the reverse process of tuple packing


We can unpack a tuple and assign its values to different variables
LIST TUPLE
LIST TUPLE

List and Tuple are exactly same except small difference: List objects are
mutable where as Tuple objects are immutable.

In both cases insertion order is preserved, duplicate objects are allowed,


heterogenous objects are allowed, index and slicing are supported.

LIST VS TUPLE
LIST TUPLE
When to use a Tuple instead of List

 Program execution is faster when manipulating a tuple than it is for the


equivalent list. (This is probably not going to be noticeable when the list or
tuple is small.)

 Sometimes you don’t want data to be modified. If the values in the collection
are meant to remain constant for the life of the program, using a tuple LIST VS TUPLE
instead of a list guards against accidental modification.

 There is another Python data type that you will encounter shortly called a
dictionary, which requires as one of its components a key that is of an
immutable type. A tuple can be used for this purpose, whereas a list can’t be.
Tuple Space / Size

Some of you are thinking that how tuples are efficient in space or how it
is faster than list then here is the proof we are doing programmatically
to show this .
Tuple Space / Size
Tuple Execution Time
Programming Lab - 26

71. WAP to convert tuples into list and vice versa

72. WAP to check if the element is present in tuple or not

73. WAP to update a value in tuple


AC T i Vi T Y Ti M E

a
b
c
d
DICTIONARY

KEYS VALUES
{}
DICTIONARY

Dictionary = {
Like a real-life dictionary has words and meanings, Python Key : value,
Key : value,
dictionaries have keys and values. They are an important data Key : value
structure in Python and we will learn how to create, access, }

manipulate and use them.

If we want to represent a group of objects as key-value pairs then


we should go for Dictionary.
{ DICTIONARY}
Dictionaries are in curly brackets.

Key-value pairs are separated by commas and keys and values are
separated by colons. Keys in dictionaries are unique and immutable.

Unlike other data structures, dictionaries hold two items in pairs


instead of a single item. This is like a real-life dictionary. You can
search for a value if you know the key. One key cannot have two
values.
{ DICTIONARY}
Example

Think of a phone book. You have names of people and the phone
numbers associated to those people. A dictionary is exactly the data
structure you need if you want to implement a phone book. Dictionary

A phone book is nothing more than a collection of name: phone


number pairs.
Similarly, a dictionary is a collection of key: value pairs.
{ DICTIONARY}
Points to Remember

 Duplicate keys are not allowed but values can be duplicated.


 Heterogeneous objects are allowed for both key and values. IMPORTANT
 insertion order is not preserved
 Dictionaries are mutable
 Dictionaries are dynamic
 indexing and slicing concepts are not applicable

Note: In C++ and Java Dictionaries are known as "Map"


{}
DICTIONARY

Creating Dictionaries Removing Items

Accessing Items Changing Values

Adding Items Copying Dictionaries


CREATION OF DICTIONARY

Create an empty Dictionary KEYS : VALUES


CREATION OF DICTIONARY

We can add entries as follows KEYS : VALUES


CREATION OF DICTIONARY

If we know data in advance then we can create dictionary as KEYS : VALUES


follows
CREATION OF DICTIONARY

If we know data in advance then we can create dictionary as KEYS : VALUES

follows
CREATION OF DICTIONARY

Dictionary with Mixed Keys KEYS : VALUES


ACCESS ELEMENTS OF DICTIONARY

Keys Values
‘A’ apple
When working with a python dictionary, it is sometimes necessary to
‘B’ Ball
access dictionary data such as keys, values and items (key-value
‘C’ Cat
pairs). Access to this data can take place in various ways.

The methods below can be applied to access a certain value from a


dictionary.
ACCESS ELEMENTS OF DICTIONARY

Keys Values
Using Square brackets ‘A’ apple

‘B’ Ball
To access dictionary elements, you can use square brackets along ‘C’ Cat

with the key to obtain its value.


ACCESS ELEMENTS OF DICTIONARY

Keys Values
Using Square brackets ‘A’ apple

‘B’ Ball
If the given key does not exist in the dictionary, Python raises a Key ‘C’ Cat

Error exception.
AC T i Vi T Y Ti M E

1. WAP to enter name and percentage marks in a dictionary and


display information on the screen
TO UPDATE DICTIONARY

dict[key] = value

If the key is not available then a new entry will be added to the
dictionary with the specified key-value pair

If the key is already available then old value will be replaced with
new value.
TO UPDATE DICTIONARY
DELETE IN DICTIONARY

You can delete an entire dictionary. Also, unlike a tuple, a Python


dictionary is mutable. So you can also delete a part of it.

1. Deleting an entire Python dictionary

2. Deleting a single key-value pair


DELETE IN DICTIONARY
Keys Values

‘Name’ Tapsee
1. Deleting an entire Python dictionary
‘Gender’ Female

To delete the whole Python dict, simply use its name after the
keyword ‘del’.
DELETE IN DICTIONARY
Keys Values

‘Name’ Tapsee
2. Deleting a single key-value pair ‘Gender’ Female

To delete just one key-value pair, use the keyword ‘del’ with the key
of the pair to delete.
DICTIONARY METHODS

clear() 1 6 keys()

copy() 2 7 update()

get() 3 8 pop()

Items() 4 9 values()

fromkeys() 5 10 popitem()
1. CLEAR()

1 clear()
clear() removes all the key-value pairs of a dictionary.
2. COPY()

2 copy()
To create exactly duplicate dictionary(cloned copy)
3. GET()

To get the value associated with the key 3 get()

d.get(key)
If the key is available then returns the corresponding value otherwise
returns None . It wont raise any error.

d.get(key,defaultvalue)
If the key is available then returns the corresponding value otherwise
returns default value.
3. GET()
4. ITEMS()

It returns list of tuples representing key-value pairs. 4 Items()


5. FROMKEYS()

This method takes keys from an iterable and creates a new dictionary
5 fromkeys()
from it.
6. KEYS()

It returns all keys associated with dictionary


6 keys()
7. UPDATE()

7 update()
All items present in the dictionary d2 will be added to dictionary d1
8. POP()

d1.pop(key) 8 pop()
It removes the entry associated with the specified key and returns the
corresponding value

If the specified key is not available then we will get KeyError


9. VALUES()

9 values()
It returns all values associated with the dictionary
10. POPITEM()

This removes the last added key-value pair from a dictionary and 10 popitem()
returns it.

It returns KeyError if Dictionary is Empty


{}
DICTIONARY

a
b
c
d
Programming Lab - 27

74. WAP to Input keys and values and update

75. WAP to Input keys and values and delete

76. WAP to Input keys and values and search


Programming Lab - 28

77. WAP to Input keys and values from the keyboard and print the
sum of values ?

78. WAP to find number of occurrences of each letter present in


the given string ?
SETS

Sets
Sets are used to store multiple items in a single variable.
PYTHON

Set is one of 4 built-in data types in Python used to store collections


of data, the other 3 are List, Tuple, and Dictionary, all with different
qualities and usage.

Note: Set items are unchangeable, but you can remove items and
add new items.
SET

An item appears only once in a set, no matter how many times it is


added.

Set
{1,2,3,4}
SETS
1 Duplicates are not allowed.

2 Insertion order is not preserved . But we can sort the elements.

3 Indexing and slicing not allowed for the set.

4 Heterogeneous elements are allowed.

5 Set objects are mutable i.e once we creates set object we can perform any changes in that
object based on our requirement.

6 We can represent set elements within curly braces and with comma separation

7 We can apply mathematical operations like union, intersection, difference etc on set objects.
CREATION OF SET

1. Directly with Curly Braces if we know the elements


CREATION OF SET

2. We can create set objects by using set() function


S = set(any sequence)
SET

a
b
c
d
CONCLUSION

If your answer is Set then your situation may be like Rajpal Yadav
CONCLUSION
CREATION OF SET

Note: While creating empty set we have to take special care.


Set
Compulsory we should use set() function. PYTHON

S = {} ==> It is treated as dictionary but not empty set.


IMPORTANT FUNCTIONS OF SETS
1. ADD()

1 add()
Adds item to the set
2. UPDATE()

To add multiple items to the set. 2 update()


Arguments are not individual elements and these are Iterable
objects like List , range etc. All elements present in the given Iterable
objects will be added to the set.
3. COPY()

Returns copy of the set. 3 copy()


It is cloned object.
4. POP()

It removes and returns some random element from the set. 4 pop()
5. REMOVE()

It removes specified element from the set. 5 remove()


If the specified element not present in the Set then we will get
KeyError
6. DISCARD()

It removes the specified element from the set. 6 discard()


If the specified element not present in the set then we won't get any
error.
7. CLEAR()

To remove all elements from the Set. 7 clear()


Lets Discuss

Q. What is the difference between remove() and discard() functions


in Set?

Q. Explain differences between pop() and remove() functions in Set?


ADD() UPDATE()

add VS update
We can use add() to add individual item to the Set
where as we can use update() function to add multiple items to Set.

add() function can take only one argument


where as update() function can take any number of arguments but
all arguments should be iterable objects
SETS

a
b
c
d
MATHMATICAL OPERATIONS
FOR SETS

Union Difference Intersection


MATHMATICAL OPERATIONS
FOR SETS

UNION
s1.union(s2) ==>We can use this function to return all elements
present in both sets
s1.union(s2) or s1|s2
MATHMATICAL OPERATIONS
FOR SETS

INTERSECTION
s1.intersection(s2) or s1&s2
Returns common elements present in both s1 and s2
MATHMATICAL OPERATIONS
FOR SETS

DIFFERENCE
x.difference(y) or x-y
returns the elements present in x but not in y
Programming Lab - 29

79. WAP to eliminate duplicates present in the list?

80. WAP to print different vowels present in the given word

Note : By using sets()


FROZEN SET

FROZEN SET
IN
PYTHON
FROZEN SET

It is exactly same as set except that it is immutable.


Hence we cannot use add or remove functions.

frozenset( [1,2,3,4] )

iterable
FROZEN SET

Frozen set is just an immutable version of a Python set object. While


elements of a set can be modified at any time, elements of the
frozen set remain the same after creation.

Due to this, frozen sets can be used as keys in Dictionary or as


elements of another set.
HOW TO CREATE FROZEN SET

s = {10,20,30,40}

fs = frozenset(s)

This fs is freezed
HOW TO CREATE FROZEN SET
Programming Lab - 30

81. WAP to calculate Number of Digits in a Number

82. WAP to calculate Cube of Each Digit in a Number


for Example Input = 123
output = 3³ = 27
2³ = 8
1³ = 1
Programming Lab - 31

83. WAP to calculate Power of Each Digit in a Number Where value


of Power = Number of Digits in a Number
for Example Input = 1234 here, Number of Digits is 4

That means Power = 4,


So the Preferred output will be
4⁴ = 256
3⁴ = 81
2⁴ = 16
1⁴ = 1
Programming Lab - 32

Now Based on Previous 3 Programs you can able to do the Next one
Which is

84. To Check Whether a Number is Armstrong or not.

153

13 53 33 153
Programming Lab - 33

85. To Check Whether a Number is Perfect or not.


SUMMARY
SUMMARY
We have completed the Basics of python and Basic Data Structure in of
which is the foundation of learning python.

Now as the next step we are going to build Multistory Building to that
foundation

All the Best !


ADVANCED

PYTHON

 Functions – Filter , Map , Reduce , Lambda


 Recursion
 Modules
 Packages
 File Handling
 Exception Handling
 Object Oriented Python
 Decorator & Generator
 Deep dive in String (Logic Building)
Syllabus

PYTHON

 Basic Fundamentals of Python  Functions – Filter , Map , Reduce , Lambda


 Data types  Recursion
 Int float list tuple dict set frozentset  Modules
 Flow Control (Loops , if else, break , pass)  Packages
 Type Casting  File Handling
 Immutablity vs Mutablity  Exception Handling
 String  Object Oriented Python
 Slicing  Decorator & Generator
 Interview Preparation  Deep dive in String (Logic Building)
THANK YOU

You might also like