[go: up one dir, main page]

0% found this document useful (0 votes)
105 views207 pages

Unit I

Uploaded by

Upendra Neravati
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)
105 views207 pages

Unit I

Uploaded by

Upendra Neravati
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/ 207

RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

PYTHON PROGRAMMING

UNIT-1
Introduction: History of Python, Need of Python Programming, Applications Basics of
Python Programming Using the REPL(Shell), Running Python Scripts, Variables,
Assignment, Keywords, Input-Output, Indentation. Overview on Fundamental data
types of Python.

Operators in Python: Arithmetic Operators, Comparison (Relational) Operators,


Assignment Operators, Logical Operators, Bitwise Operators, Shift Operators,
Ternary operator, Membership Operators, Identity Operators, Expressions and order
of evaluations. Illustrative examples on all the above operators.

INTRODUCTION TO PYTHON:
➢ A program (computer program) is a set/sequence of instructions written in a
computer programming language instructing a computer to do specific tasks.
➢ “Software” is a generic term used to describe computer programs.
➢ A programming language is a computer language engineered to communicate
and provide instructions to a machine (computers).
➢ Types of Programming languages:
o High-level Language: [closure to the human languages]
▪ Close to Business problems-writing banking software, building an
e-commerce website, etc
▪ Ex: Python, C, C++, Perl, Java, Ada, JavaScript, Ruby, etc.
o Low-level Language: [closure to Hardware]
▪ Close to the system's problems-writing a device driver, memory
manager, anti-virus, etc
▪ Ex: Assembly level language, and Machine level language

DEPARTMENT OF MECHANICAL ENGINEERING


~1~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Translation:

High-level Programming Languages


Advantages:

➢ Easier to program.

➢ Less time to write

➢ Shorter and easier to read, and they are more likely to be correct.

➢ High-level languages are portable

Disadvantage:

➢ Programs have to be processed before they can run. This extra processing takes
some time

Program Processes: Interpreters and Compilers

DEPARTMENT OF MECHANICAL ENGINEERING


~2~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Interpreters Compilers
It takes a single line of code It takes an entire program at
Input
or instruction at a time. a time.
It does not produce any It generates intermediate
Output
intermediate object code. object code.
Compilation and execution The compilation is done
Working mechanism
take place simultaneously. before execution.
Speed Slower Comparatively faster
It requires less memory as it Memory requirement is more
Memory does not create intermediate due to the creation of object
object code. code.
Display all errors after
Displays error of each line
Errors compilation, all at the same
one by one.
time.

Error detection Easier comparatively Difficult

➢ Python is a General Purpose (multiple purposes) High-Level Programming Language.

➢ General Purpose means Python is not specific to a particular area, happily we can
use Python for any type of application areas.

➢ For example:

o Desktop Applications o Network Programming


o Games and 3D Graphics (Movie
o Web Applications and internet
creation)
development
o Console-based Applications
o Data Science Applications
o Computer Vision
o Machine learning application o Machine Learning

o Science and Numeric Applications o Robotics

o Software Development Application o Data Analysis/Data processing

o Python Applications in Education o Signal processing

o Python Applications in Business (ERP) o Music software

o Database Access
➢ High-level programming languages are programmer-friendly languages, but not the
machine-friendly languages

DEPARTMENT OF MECHANICAL ENGINEERING


~3~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

➢ Need not worry about the low-level things i.e., memory management, security,
destroying the objects, and so on.

➢ Python is considered an interpreted language because Python programs are


executed by an interpreter. There are two ways to use the interpreter:

o Command-line mode and

o Script mode (IDLE).

➢ In command-line mode, you type Python programs, and the interpreter prints the
result:

➢ >>> ->which is the prompt the interpreter uses to indicate that it is ready

(The >>> prompt is the Python interpreter’s way of asking you, “What do you want
me to do next?)

➢ Alternatively, you can write a program in a file and use the interpreter to execute the
contents of the file. Such a file is called a script.

Debugging:
➢ Programming is a complex process, and because it is done by human beings, it often
leads to errors.

➢ Programming errors are called bugs and the process of tracking them down and
correcting them is called debugging.

DEPARTMENT OF MECHANICAL ENGINEERING


~4~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

➢ Kinds of errors can occur in a program:

✓ Syntax errors: are like grammatical errors in English. Python has its own syntax.

Syntax refers to the structure of a program and the rules about that structure. They
occur when the defined rules are not followed.

For example,

▪ If a quotation mark is missing or a word is misspelled—python will report syntax


errors.

▪ Mistyping a statement,

▪ Incorrect indentation,

▪ Omitting some necessary punctuation, or using an opening parenthesis without


a corresponding closing parenthesis.

These errors are usually easy to detect because Python tells you where they are and what
caused them.

Identify the syntax error in the following statements:

prnt("Python is Easy")

Print("Python is not Typhoon")

Runtime errors

✓ The error does not appear until you run the program. These errors are also called
exceptions because they usually indicate that something exceptional (and bad) has
happened.

✓ Runtime errors are errors that cause a program to terminate abnormally. They occur
while a program is running if the Python interpreter detects an operation that is
impossible to carry out. Input mistakes typically cause runtime errors. An input error
occurs when the user enters a value that the program cannot handle. would cause a
runtime error

❑ If the program expects to read in a number, but instead the user enters a string
of text, this causes data-type errors to occur in the program.

❑ Division by zero for integer divisions

DEPARTMENT OF MECHANICAL ENGINEERING


~5~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Semantic errors (logic errors)


✓ It will run successfully, and will not generate any error messages, but it will not do
the right thing. It will do something else.

✓ For example, suppose you wrote the program to convert a temperature (35
degrees) from Fahrenheit to Celsius.

# Convert Fahrenheit to Celsius

print("Fahrenheit 35 is Celsius degree ")

print(5 / 9 * 35 - 32)

WHAT’S THE DIFFERENCE BETWEEN SCRIPTING AND


PROGRAMMING LANGUAGES?
➢ Some scripting languages traditionally used without an explicit compilation step

✓ Ex: JavaScript, PHP, Python, VBScript, Shell script, Perl.

➢ Some programming languages traditionally used with an explicit compilation step

✓ Ex: C, C++, Java.

➢ Basically, All scripting languages are programming languages, but all programming
languages are not scripting languages.

CURRENT POPULARITY

DEPARTMENT OF MECHANICAL ENGINEERING


~6~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

WHY PYTHON SUDDENLY BECAME POPULAR?

DEPARTMENT OF MECHANICAL ENGINEERING


~7~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

HISTORY OF PYTHON

➢ Python was conceived (Conceptualized) in late 1980 by Guido van Rossum at


Centrum Wiskunde & Informatics (CWI) is the National Research Institute for
Mathematics and Computer Science in the Netherlands, Amsterdam.

➢ When he began implementing python, Guido van Rossum was also reading the
published scripts from “Monty Python’s Flying circus” a BBC comedy series from the
1970s. Van Rossum thought he needed a name that was short, unique, and slightly
mysterious, so he decided the language python.

➢ Python was developed in 1989 while working at National Research Institute at the
Netherlands.

➢ But officially python was made available to the public is: Feb 20th, 1991.

➢ Developed python language by taking almost all programming features from different
languages

➢ Functional programming features from C

➢ OOP’s features from C++

➢ Scripting language features from Perl and shell script

➢ Modular programming features from Modula-3.

Most of the syntax is derived from C and ABC languages.

PYTHON AS SCRIPTING LANGUAGE:

Scripting language means a group of lines of code will be executed line by line.

No functions concept, No classes concept, just a group of lines will be executed one by
one.

print("RGMCET, Nandyal")
print("Autonomous Engineering college")
print("Department of Mechanical Engineering")

DEPARTMENT OF MECHANICAL ENGINEERING


~8~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

print("Python Programming")
print("Python is a Scripting language")
Output:
RGMCET, Nandyal
Autonomous Engineering college
Department of Mechanical Engineering
Python Programming
Python is a Scripting language

PYTHON AS A FUNCTIONAL PROGRAMMING LANGUAGE

def f():
print("RGMCET, Nandyal")
print("Autonomous Engineering College")
print("Department of Mechanical Engineering")
print("Python programming")
print("Python is a scripting language")
f()
Output:
RGMCET, Nandyal
Autonomous Engineering college
Department of Mechanical Engineering
Python Programming
Python is a scripting language

PYTHON AS AN OBJECT-ORIENTED PROGRAMMING LANGUAGE

Python supports Object-oriented programming features like classes, objects, abstraction,


encapsulation, inheritance, polymorphism, etc. hence python is an object-oriented
programming language

Without creating an object:

class python:
def designer():
print("Guido Van Rossum")
python.designer()

DEPARTMENT OF MECHANICAL ENGINEERING


~9~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Output:

Guido Van Rossum

With creating object:

class python:

def designer():

print("Guido Van Rossum")

p=python

p.designer()

Output:

Guido Van Rossum

In order to access the function inside the class all you have to do call the class with its
class name and with the “.” dot operator call its function. We can access the class in two
ways: Without creating the object and creating an object.

FEATURES OF PYTHON

Simple and easy to learn


➢ Python is a simple programming language. When we read the Python program, we
can feel like reading English statements.

Python program: Java program:

for i in range(10): for(int i=0;i<10;i++){

print(i) System.out.println(i);

➢ The syntaxes are very simple and only 30+ (35 in python3.10.2) keywords are
available (in Java 53).
➢ When compared with other languages, we can write programs with a very less
number of lines. Hence more readability and simplicity.
➢ We can reduce the development and cost of the project

DEPARTMENT OF MECHANICAL ENGINEERING


~ 10 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Freeware and Open Source:


➢ We can use Python software without any license and it is freeware.

➢ freeware means we are not required to pay a single paisa for license-related issues

➢ Its source code is open so that we can customize based on our requirements.

➢ Open source means we can able to see source code how it is implemented, and we
can customize as per our requirement and you can introduce your python version.

➢ Eg: Jython is a customized version of Python to work with Java Applications.

High-Level Programming language:


➢ Python is a high-level programming language and hence it is a programmer-friendly
language.

➢ Being a programmer we are not required to concentrate on low-level activities like


memory management and security etc..

Platform Independent:-> Write Once Run Anywhere (WORA)


➢ Once we write a Python program, it can run on any platform without rewriting once
again. (Write a program in windows machine, it can run on any machine-like Linux,
Unix, Sun Solaris, Mac machine, etc)

➢ Internally PVM is responsible to convert into machine-understandable form.

Portability:
➢ Python programs are portable. i.e we can migrate from one platform to another
platform very easily. Python programs will provide the same results on any platform.

Dynamically Typed:
➢ In Python we are not required to declare the type for variables. Whenever we are
assigning the value, based on value, the type will be allocated automatically. Hence
Python is considered a dynamically typed language.

➢ But Java, C, C++, etc are Statically Typed Languages b'z we have to provide type at
the beginning only.

➢ This dynamic typing nature will provide more flexibility to the programmer.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 11 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Both Procedure Oriented and Object-Oriented:


Python language supports both Procedure oriented (like C, pascal etc) and object-oriented
(like C++,Java) features. Hence, we can get benefits of both like security and reusability
etc.

Interpreted:
➢ We are not required to compile Python programs explicitly. Internally Python
interpreter will take care that compilation.

➢ If compilation fails interpreter raised syntax errors. Once compilation success then
PVM (Python Virtual Machine) is responsible to execute.

Extensible:
➢ We can use other language programs in Python [ Java code can be used in Python
using ‘Jython’, C# code can be accessed using Iron python].

• Let us assume that some C program is there, some Java program is there, can we
use these applications in our Python program or not?

• yes, we can use other language programs in Python.

What is the need for that?

1. Suppose We want to develop a Python application, assume that some xyz functionality
is required to develop the Python application.

2. There is some java code is already there for this xyz functionality. It is non-python
code. Is it possible to use this non-python code inside our python application?

Yes, No problem at all.

➢ The main advantages of this approach are:

1. We can use already existing legacy non-Python code

2. We can improve performance of the application

Embedded:
• We can use Python programs in any other language programs. i.e we can embed
Python programs anywhere.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 12 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

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. etc...

Ex: Write a Python program to generate 6 digit OTP

• In Python to generate random numbers already a library is available. By making use


of that library we can write the code in an easy manner.

from random import randint


for i in range(1,11):

print(randint(0,9),randint(0,9),randint(0,9),randint(0,9),randint
(0,9),randint(0,9),sep = '')

Output:
228945 485642 168720 159855 282881 165049 962630 473469 371343 744817
Conclusions
➢ These are the 11 key features of Python programming language. Out of 11 Key
features, 3 Key features are specific to Python

▪ Dynamically Typed

▪ Both Procedural Oriented and Object-Oriented

▪ Extensive Library

➢ These 3 Features are not supported by any other programming languages like
C,C++ and Java etc.,

LIMITATIONS OF PYTHON:

➢ Suppose We want to develop mobile applications; Python is the worst choice. Why?

The main reason for this is Python, as of now, does not have library support to develop
mobile applications.

Which programming language is the best choice for mobile applications?

Android, IOs Swift are the kings in the Mobile application development domain.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 13 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

➢ Suppose We want to develop Enterprise applications such as Banking, Telecom


applications where multiple services are required (For ex, transaction management,
Security, Messaging etc.,).

To develop these end-to-end applications Python is not the best suitable, because, Python
doesn't have that much Library support to develop these applications as of now.

➢ We have already discussed that Python is interpreted programing language, here


execution can be done line by line. That's why the performance-wise Python is not
good and not up to the mark.

To improve performance, Now people have added the JIT compiler to the PVM. This works
in the following manner:

• Instead of interpreting line by line every time, a group of lines will be interpreted
only once and every time that interpreted code is going to use directly. JIT compiler
is responsible to do that.

• JIT compiler + PVM flavor is called pypy for better (Python for speed) version.

BASICS OF PYTHON PROGRAMMING USING THE REPL (SHELL)

➢ Python’s shell provides an interface for the users to interact with the Python
interpreter.

➢ Python provides a Python Shell (also known as Python Interactive Shell) which is used
to execute a single Python command and get the result.

➢ Python Shell waits for the input command from the user. As soon as the user enters
the command, it executes it and displays the result.

➢ REPL is the language shell, the Python Interactive Shell. The REPL acronym is short
for Read, Eval, Print and Loop.

➢ The process is:

Read: take user input.

Eval: evaluate the input.

Print: shows the output to the user.

Loop: repeat.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 14 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

How to Quit the Python Shell


To exit from the Python shell and go back to the command prompt or terminal, either
type quit ( ) or exit( ). → short cut is: Ctrl+D

Running Python Scripts

A Python script is a file containing multiple lines of Python code saved with .py extension.

A Python script can be directly executed line by line without any need to compile it.

IDENTIFIERS

A name in a Python program is called an identifier.

It can be a class name or function name or module name or variable name.

All identifiers must obey the following rules:

➢ An identifier is a sequence of characters that consists of letters (Either lower case [ a


to z] or upper case [A to Z), digits (0 to 9), and underscores (_).

➢ An identifier must start with a letter or an underscore. It cannot start with a digit.

➢ An identifier cannot be a keyword. Keywords, also called reserved words, have


special meanings in Python.

For example, import is a keyword, which tells the Python interpreter to import a module to
the program.

➢ An identifier can be of any length. Identifiers are case-sensitive. Of course, Python


language is case sensitive language.

➢ One cannot use spaces and special symbols like !, @, #, $, % etc. as identifiers.

VARIABLE

➢ A variable can be considered as a storage container for data.

➢ Variables are used to reference values that may be changed in the program.

➢ A variable is the way to store data while making it easy to refer to it later in our
code.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 15 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

VARIABLE NAMING CONVENTIONS

➢ A variable name must begin with either a letter or an underscore(_) followed by letters,
numbers, or underscore & unlimited in length.

➢ Variable names are case-sensitive. Ex: age and Age are not the same.

➢ Variable names conventionally have lower-case letters, with multiple words separated
by underscores. Ex: this_is_a_variable, simple_interest, date_of_birth, etc… are valid
variables. This is called the snake case.

➢ Variable names cannot be keywords & cannot start with numbers & cannot use
special symbols like !, @, #, $, % etc.

Ex: Program: Average of three numbers using variables.

a = 3
b = 4
c = 5
avg = (a + b + c) / 3
print(avg)
4.0
Ex: Program: Calculate the simple interest when principal, interest rate and tenure are
given.

principal = 100000
tenure = 12
rate_of_interest = 0.05

simple_interest = (principal * tenure * rate_of_interest) / 100


print(simple_interest)
600.0
Note

It is always a good practice to choose descriptive names for variables. By looking at the
variable, one should be able to understand the purpose of it.

print() is an output function in python and is used to display output on the console or shell.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 16 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

PYTHON ASSIGNMENT STATEMENTS

➢ The assignment statement creates new variables and gives them values.

➢ It is the only statement that does not start with a keyword.

➢ Basic assignment statement in Python is :

➢ Syntax: <variable> = <expr>

➢ Where the equal sign (=) is used to assign value (right side) to a variable name (left
side).

>>> Item_name = "Computer" #A String


>>> Item_qty = 10 #An Integer
>>> Item_value = 1000.23 #A floating point
>>> print(Item_name)
Computer
>>> print(Item_qty)
10
>>> print(Item_value)
1000.23
>>>

Multiple Assignment
The basic assignment statement works for a single variable and a single expression.

Syntax:

var1=var2=var3...varn= = <expr>

Example:

x = y = z = 1

Now check the individual value in Python Shell.

>>> x = y = z = 1
>>> print(x)
1
>>> print(y)
1

DEPARTMENT OF MECHANICAL ENGINEERING


~ 17 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

>>> print(z)
1
>>>
Syntax:
<var>, <var>, ..., <var> = <expr>, <expr>, ..., <expr>
Example:
x, y, z = 1, 2, "abcd"

In the above example x, y and z simultaneously get the new values 1, 2 and "abcd".

>>> x,y,z = 1,2,"abcd"


>>> print(x)
1
>>> print(y)
2
>>> print(z)
abcd

SWAP VARIABLES
Swapping two variables refers to mutually exchanging the values of the variables.
Generally, this is done with the data in memory.
Syntax:
var1, var2 = var2, var1
Example:
>>> x = 10
>>> y = 20
>>> print(x)
10
>>> print(y)
20
>>> x, y = y, x
>>> print(x)
20
>>> print(y)
10

DEPARTMENT OF MECHANICAL ENGINEERING


~ 18 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

KEYWORDS IN PYTHON

➢ Keywords are the reserved words, used to define the syntax and structure of the
Python language.

➢ These are reserved words with special meaning and purpose. They are used only for
the intended purpose.

➢ The interpreter uses the keywords to recognize the structure of the program

➢ Keywords cannot be used as

o Variable names,
o Function names or
o Any other identifiers.

>>> import keyword

>>> print(keyword.kwlist)

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',


'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']

Key points:

▪ Switch concept is not there in python

▪ do while loop is not there in python

▪ Int, float, char and double are not reserved words

INPUT-OUTPUT

We have two functions to handle input from a user and system in Python.

• input(prompt) to accept input from a user (to get the input from the user).

The input() function reads a line entered on a console by an input device such as a
keyboard and converts it into a string and returns it.

Input Using Mouse Click or movement, i.e. you clicked on the radio button or some
drop-down list and chosen an option from it.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 19 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

• print() to display output on the console.

Input ( )
Syntax: val = input(“prompt string”)

Example:

name = input("Enter Employee Name: ")


salary = input("Enter salary: ")
company = input("Enter Company name: ")
print("Printing Employee Details")
print("Name", "Salary", "Company")
print(name, salary, company)

OUTPUT:

Enter Employee Name: xyz


Enter salary: 100000
Enter Company name: RGMCET
Printing Employee Details
Name Salary Company
xyz 100000 RGMCET

Example:

x = input("Enter x value: ")


y = input("Enter y value: ")
print(x + y)
Enter x value: 20
Enter y value: 30
2030

By default, the 'input()' function builds a string from the user’s keystrokes.

x = input()
print(type(x))
56
<class 'str'>

input to be 'int' type or 'float' type

DEPARTMENT OF MECHANICAL ENGINEERING


~ 20 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

x = int(input("Enter a integer value: "))


print(x)
print(type(x))
y = float(input("Enter a float value: "))
print(y)
print(type(y))
Enter a integer value: 12
12
<class 'int'>
Enter a float value: 12
12.0
<class 'float'>

OUTPUT FUNCTION

➢ print() function used to display output on the console or shell.


➢ Syntax : print(objects)➔objects are the values to be printed.
➢ We can use commas to print multiple variables / values at a time as shown below.

x = "Apple"
y = 10
z = 21.5
print(x, y, z)
Apple 10 21.5
➢ Python print() function comes with a parameter called ‘end’.
print("Hello", end = ' ')
print("World!")
Hello World!

DIFFERENT STYLES OF PRINTING

x = -100
y = 300
z = x + y
# normal way old style of printing
print(x, "plus", y, "is", z, "and", x, "is -ve")

DEPARTMENT OF MECHANICAL ENGINEERING


~ 21 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

# using format
print("{} plus {} is {} and {} is -ve".format(x, y, z, x))
print("{0} plus {1} is {2} and {0} is -ve".format(x, y, z))
# using f-string
print(f'{x} plus {y} is {z} and {x} is -ve')

INDENTATION

➢ Indentation is used to indicate blocks of code for class and function definitions or flow
control

➢ Indentation refers to the spaces (FOUR) or Tab space (ONE) at the beginning of a
code line.

➢ The first line of the function definition is called the header, the rest is called the body.

➢ The header has to end with a colon (:) and the body has to be indented.

➢ The body can contain any number of statements.

➢ Where in other programming languages the indentation in code is for readability only,
the indentation in Python is very important. Interpreter returns Indentation Error when
we are not providing correct Indentation.

num = int(input("Enter a number: "))


if num < 0:
num = -num
print(num)
Enter a number: -5
5

OVERVIEW ON DATA TYPES

The information stored in a computer is generally referred to as data

Data Type represents the type of data present inside a variable.

▪ Data types specify the different sizes and values that can be stored in the variable.
For example, Python stores numbers, strings, and a list of values using different
data types.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 22 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

▪ In Python we are not required to specify the type explicitly. Based on the value
provided, the type will be assigned automatically and store value at some memory
location, and then binds that variable name to that memory. Hence Python is a
Dynamically Typed Language.

➢ Primitive data types: Basic building blocks

▪ Numeric types

• int - Integer type to represent Whole numbers, Ex: 20

• float - Real types are for representing numbers with a fractional part, Ex: 20.75

• complex – to represent complex numbers, Ex: 3+4j

▪ Text type

• str – to represent collection of characters, Ex: 'Apple', " Apple ", '''Apple''' , """Apple"""

▪ Bool – to represent Boolean values, Ex: True or False

Note:

o All the numbers will be treated as integers it may be positive or negative

o All the numbers with decimal values will be treated as float it may be positive or
negative

o All the characters in between the quotes (single, double or triple quotes) will
be treated as strings.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 23 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

➢ Composite data types: Combination of primitive and other data types

▪ Sequence type

• List, tuple

▪ Set type –set, frozenset

▪ Dictionary - dict

➢ Binary data types: made up of bytes

▪ bytes

▪ bytearray

▪ memoryview

➢ None data type: None is not the same as 0, False, or an empty string. None is a
data type of its own (NoneType) and only None can be None.

➢ Range type (immutable): range () syntax: range(start, stop, step)

Used to generate a sequence of numbers from a start number up to the stop


number.

For example, If we want to represent the roll number from 1 to 20, we can use
the range() type.

By default, it returns an iterator object that we can iterate using a for loop.

The most commonly used in-built functions in Python are as follows:

➢ type( ): It is to check the type of variable

➢ id( ): It is used to get the address of the object

➢ print( ): It is used to print the value

PYTHON IS A DYNAMICALLY TYPED PROGRAMMING LANGUAGE

Python is a dynamically-typed language as the data type is set to a variable when we


assign a value and run it.

x = 2 <class 'float’> print(type(x))


print(type(x)) x = 'Apple' <class 'bool’>
<class 'int’> print(type(x)) x = 2 + 3j
x = 3.5 <class 'str’> print(type(x))
print(type(x)) x = True <class 'complex'>

DEPARTMENT OF MECHANICAL ENGINEERING


~ 24 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Note: In this, the type of 'x' has changed from 'int' to 'float', float to string, string to boolean
and later to 'complex' just by changing the value and running it.

We can represent integral values in the following ways:


➢ Decimal form (base 10)

➢ Binary form (base 2)

➢ Octal form (base 8)

➢ Hexa decimal form (base 16)

Decimal form(base-10):
❑ It is the default number system in Python

❑ The allowed digits are: 0 to 9

❑ Eg: a =10

0.25 * 2 =0.50 //take 0 and move 0.50 to next step

0.50 * 2 =1.00 //take 1 and stop the process

0.25 = (01) 2

Combining both integral and fractional,

4.25 = (100.01) 2

Binary form(base-2):
▪ The allowed digits are : 0 & 1

▪ Literal ( the data that are assigned to variables or constants) value should be
prefixed with 0b or 0B

DEPARTMENT OF MECHANICAL ENGINEERING


~ 25 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Eg:

▪ a = 0B1111

▪ a =0B123

▪ a=0b111

Octal Form(base-8):
• The allowed digits are : 0 to 7

• Literal value should be prefixed with 0o or 0O.

Conversion from octal to decimal

DEPARTMENT OF MECHANICAL ENGINEERING


~ 26 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Hexadecimal Form(base-16):
• The allowed digits are : 0 to 9, a-f (both lower and upper cases are allowed)

• Literal value should be prefixed with 0x or 0X

• Ex: 0XFACE, 0Xface 0XBeef 0XBeer ×

DATA TYPES: BASE CONVERSION FUNCTIONS

Python provides three in-built functions for base conversions.

By using these base conversion functions, we can convert from one base to another base.

Note: All these base conversion functions are applicable only for Integral numbers.

bin(): We can use bin() to convert from any other base to binary
>>> bin(15)
'0b1111'
>>> bin(0o123)
'0b1010011'

DEPARTMENT OF MECHANICAL ENGINEERING


~ 27 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

>>> bin(0xface)
'0b1111101011001110'

oct(): We can use oct() to convert from any other base to octal
>>> oct(0b1011011)
'0o133'
>>> oct(0xface)
'0o175316'
>>> oct(120)
'0o170'

hex(): We can use hex() to convert from any other base to hexa decimal
>>> hex(100)
'0x64'
>>> hex(0b1010)
'0xa'
>>> hex(0o12435)
'0x151d'

Data types: float data type


We can use float data type to represent floating-point values (Number with decimal
values)

>>> f=2.345
>>> type(f)
<class 'float'>

Note: We can represent integral values in decimal, binary, octal and hexadecimal forms.
But we can represent float values only by using the decimal form.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 28 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

• We can also represent floating point values by using exponential form (scientific
notation)

• The main advantage of exponential form is we can represent big values in less memory.

• Assume that we need to store a value (12000000000000000.0)

Data types: complex data type


• Python specific special data type is known as Complex data type.

• Why does Python have this special data type?

• If you want to develop scientific applications, mathematics-based applications, and


Electrical engineering applications, this complex type is very very helpful.

• How can we represent a complex number?

• a + bj is the syntax for representing a complex number.

• The complex number representation j is it compulsory.

Eg:
3+5j
10+5.5j
0.5+0.1j

DEPARTMENT OF MECHANICAL ENGINEERING


~ 29 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

• In the real part if we use int value then we can specify that either by decimal, octal,
binary or hexadecimal form.

• But imaginary part should be specified only by using the decimal form.

>>> a=0B11+5j
>>> a
(3+5j)
>>> a=3+0B11j
SyntaxError: invalid syntax

• Even we can perform operations on complex type values.

>>> a=10+1.5j
>>> b=20+2.5j
>>> c=a+b
>>> print(c)
(30+4j)
>>> type(c)
<class 'complex'>

Note: Complex data type has some inbuilt attributes to retrieve the real part and imaginary
part

c = 10.5+3.6j
c.real ==>10.5
c.imag ==>3.6

bool data type:


• We can use this data type to represent Boolean values. The only allowed values for
this data type are: True and False (true and false are not allowed in python)

• Internally Python represents True as 1 and False as 0

b=True
type(b) =>bool
Eg:
a=10
b=20
c=a<b

DEPARTMENT OF MECHANICAL ENGINEERING


~ 30 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

print(c)==>True
True + True==>2
True - False==>1

String Data Type


➢ A string is a collection/sequence of characters or Anything that is enclosed in single
quotes, double quotes, triple single quotes or triple-double quotes is treated as a string
in python.

➢ We cannot add, delete, or modify individual characters in a string.

Ex:
s1 = 'Apple'
s2 = "Apple"
s3 = '''Apple'''
s4 = """Apple"""
print(type(s1), type(s2), type(s3), type(s4))
<class 'str'> <class 'str'> <class 'str'> <class 'str'>

STRING CONCATENATION
Concatenation means to combine or add two things together. In this case, we want to
know how to add two strings together. This is very easy in Python.

x = "Hello "
y = "World"
print(x + y)
Hello World

The ‘+’ operator concatenates the two strings into one.

Internal representation of a string

DEPARTMENT OF MECHANICAL ENGINEERING


~ 31 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

In example, 'p' is stored only once and its reference (address) is placed twice, at index 1
and 2, in the list of characters.

s = "Apple"
print(id(s[0]), id(s[1]), id(s[2]))
Output:
23140185970928 23140186340272 23140186340272

‘*’ (Asterisk) Operator (Repetition operator) for the string


This specialty is not there in other programming languages.

Name = "RGMCET"*3 print('*'*4, end =' ')


print(Name) print('Dept. of M E', end = ' ')
Output: print('*' *4)
RGMCETRGMCETRGMCET Output:
Name = 3*"RGMCET" **** Dept. of M E ****
print(Name) print('*'*14)
RGMCETRGMCETRGMCET print('Dept. of M E')
print('*'*4, end ='') print('*' *14)
print('Dept. of M E', end = '') Output:
print('*' *4) **************
****Dept. of M E**** Dept. of M E
**************

ARE STRINGS IMMUTABLE?

Yes, strings are immutable. We cannot overwrite the values of immutable objects. The
storage for a string is fixed at construction and never alters. Obviously that makes handling
strings a lot simpler.

s = "Hello World!"
print(id(s))
s = "Welcome to PythonGuru"
print(id(s))
22711488237936
22711489300080

DEPARTMENT OF MECHANICAL ENGINEERING


~ 32 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

• If we observe the output, we can see that memory addresses do not match. That means
it’s not modifying the string object; it’s creating a new string object.

Let’s try to change a single character of the string.

s = "Apple"
s[1] = 'd'
print(s)
----------------------------------------TypeError
Traceback (most recent call last)
<ipython-input-21-df9bb1f86711> in <module>()
1 s = "Apple"
----> 2 s[1] = 'd'
3 print(s)
TypeError: 'str' object does not support item assignment

We get a TypeError because strings are immutable. We can’t change the individual
characters of the string object.

An immutable object is an object that is not changeable and its state cannot be
modified after it is created.

STRING DATA TYPE


o The computer doesn’t see letters at all. Every letter you use is represented by a
number in memory.

o For example, the letter A is actually the number 65. This is called encoding. There are
two types of encoding for characters –ASCII and Unicode. ASCII uses 16 bits
for encoding whereas Unicode uses 32 bits. Python uses Unicode for character
representation.

o An individual character within a string is accessed using an index.

o Index starts from 0 to n-1, where n is the number of characters in the string.

o Python allows negative indexing in strings. The index of -1 refers to the last item in
the string, -2 refers to the second last item , and so on.

o In Python, a string of length 1 is treated as a character.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 33 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Printable characters-ASCII values

Glyph Glyph
Binary Oct Dec Hex Binary Oct Dec Hex
1963 1965 1967 1963 1965 1967
010 0000 040 32 20 space 100 1001 111 73 49 I
010 0001 041 33 21 ! 100 1010 112 74 4A J
010 0010 042 34 22 " 100 1011 113 75 4B K
010 0011 043 35 23 # 100 1100 114 76 4C L
010 0100 044 36 24 $ 100 1101 115 77 4D M
010 0101 045 37 25 % 100 1110 116 78 4E N
010 0110 046 38 26 & 100 1111 117 79 4F O
010 0111 047 39 27 ' 101 0000 120 80 50 P
010 1000 050 40 28 ( 101 0001 121 81 51 Q
010 1001 051 41 29 ) 101 0010 122 82 52 R
010 1010 052 42 2A * 101 0011 123 83 53 S
010 1011 053 43 2B + 101 0100 124 84 54 T
010 1100 054 44 2C , 101 0101 125 85 55 U
010 1101 055 45 2D - 101 0110 126 86 56 V
010 1110 056 46 2E . 101 0111 127 87 57 W
010 1111 057 47 2F / 101 1000 130 88 58 X
011 0000 060 48 30 0 101 1001 131 89 59 Y
011 0001 061 49 31 1 101 1010 132 90 5A Z
011 0010 062 50 32 2 101 1011 133 91 5B [
011 0011 063 51 33 3 101 1100 134 92 5C \ ~ \
011 0100 064 52 34 4 101 1101 135 93 5D ]
011 0101 065 53 35 5 101 1110 136 94 5E ↑ ^
011 0110 066 54 36 6 101 1111 137 95 5F ← _
011 0111 067 55 37 7 110 0000 140 96 60 @ `
011 1000 070 56 38 8 110 0001 141 97 61 a
011 1001 071 57 39 9 110 0010 142 98 62 b
011 1010 072 58 3A : 110 0011 143 99 63 c
011 1011 073 59 3B ; 110 0100 144 100 64 d
011 1100 074 60 3C < 110 0101 145 101 65 e
011 1101 075 61 3D = 110 0110 146 102 66 f
011 1110 076 62 3E > 110 0111 147 103 67 g
011 1111 077 63 3F ? 110 1000 150 104 68 h
100 0000 100 64 40 @ ` @ 110 1001 151 105 69 i
100 0001 101 65 41 A 110 1010 152 106 6A j
100 0010 102 66 42 B 110 1011 153 107 6B k
100 0011 103 67 43 C 110 1100 154 108 6C l
100 0100 104 68 44 D 110 1101 155 109 6D m
100 0101 105 69 45 E 110 1110 156 110 6E n
100 0110 106 70 46 F 110 1111 157 111 6F o
100 0111 107 71 47 G 111 0000 160 112 70 p
100 1000 110 72 48 H 111 0001 161 113 71 q

DEPARTMENT OF MECHANICAL ENGINEERING


~ 34 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Glyph Glyph
Binary Oct Dec Hex Binary Oct Dec Hex
1963 1965 1967 1963 1965 1967
111 0010 162 114 72 r 111 1001 171 121 79 y
111 0011 163 115 73 s 111 1010 172 122 7A z
111 0100 164 116 74 t 111 1011 173 123 7B {
111 0101 165 117 75 u 111 1100 174 124 7C ACK ¬ |
111 0110 166 118 76 v 111 1101 175 125 7D }
111 0111 167 119 77 w ~
111 1110 176 126 7E ESC |
111 1000 170 120 78 x

TYPE CASTING: INTRODUCTION AND int() FUNCTION

➢ The process of converting the value from one type to another type is known as
Type casting or Type Conversion.

➢ Python provides 5 in-built functions, which are used to convert the values from one
type to another type. These are listed as below:

▪ int()
▪ float()
▪ complex()
▪ bool()
▪ str()

int ( ): We can use int() function to convert other type values to int type.
print(int(5))
5
print(int(5.556))
5
print(int('10'))
10
print(int(True))
1
print(int(10.0+0.15j))
Traceback (most recent call last):
File "./prog.py", line 1, in <module>
TypeError: can't convert complex to int

DEPARTMENT OF MECHANICAL ENGINEERING


~ 35 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

print(int('10.5'))
Traceback (most recent call last):
File "./prog.py", line 1, in <module>
ValueError: invalid literal for int() with base 10: '10.5’
print(int('0b111'))
Traceback (most recent call last):
File "./prog.py", line 1, in <module>
ValueError: invalid literal for int() with base 10: '0b111'

Note:

➢ We can convert from any type to int except complex type.

➢ If we want to convert str type to int type, compulsory str should contain only integral
value and should be specified in base-10

float (): We can use float() function to convert other type values to float type .
print(float(5))
5.0
print(float(5.556))
5.556
print(float('10.5’))
10.5
print(float(True))
1.0
print(float(10.0+0.15j))
Traceback (most recent call last):
File "./prog.py", line 1, in <module>
TypeError: can't convert complex to float
print(float('0b111’))
Traceback (most recent call last):
File "./prog.py", line 1, in <module>
ValueError: could not convert string to float: '0b111’
print(float('ten’))
Traceback (most recent call last):
File "./prog.py", line 1, in <module>
ValueError: could not convert string to float: 'ten'

DEPARTMENT OF MECHANICAL ENGINEERING


~ 36 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Note:

➢ We can convert from any type to float except complex type.

➢ If we want to convert str type to float type, compulsory str should contain only
integral or floating point value and should be specified in base-10

complex (): We can use complex() function to convert oth er types to complex
type.

There are two forms of complex() function is there.

Form 1 : complex(x)

We can use this function to convert x into complex number with real part x and imaginary
part 0.

print(complex(10))
(10+0j)
print(complex(0b111))
(7+0j)
print(complex(10.5))
(10.5+0j)
print(complex(True))
(1+0j)
print(complex(False))
0j
print(complex('10.5’))
(10.5+0j)
print(complex('ten'))
Traceback (most recent call last):
File "./prog.py", line 2, in <module>
ValueError: complex() arg is a malformed string

Form 2: complex(x,y) :We can use this method to convert x and y into complex number
such that x will be real part and y will be imaginary part.

print(complex(10,20))
(10+20j)
print(complex(0b111,0b1011))

DEPARTMENT OF MECHANICAL ENGINEERING


~ 37 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

(7+11j)
print(complex(10.5, 20.6))
(10.5+20.6j)
print(complex(True, True))
(1+1j)
print(complex(False, True))
1j
print(complex('10.5', '20.3'))
Traceback (most recent call last):
File "./prog.py", line 6, in <module>
TypeError: complex() can't take second arg if first is a string
print(complex(10.5, '20.3’))
Traceback (most recent call last):
File "./prog.py", line 2, in <module>
TypeError: complex() second arg can't be a string

Note:

1. can't take second arg if first is a string

2. second arg can't be a string

bool( ): We can use this function to convert other type values to bool type.

If we pass integer arguments True


print(bool('no’))
print(bool(1))
True
True
print(bool(' ’))
print(bool(10))
True
True
print(bool(‘’))
print(bool(-10))
False
True
print(bool(0))
If we pass floating type arguments
False
print(bool(1.02))
If we pass str type arguments
print(bool('True')) True
True print(bool(10.05))
print(bool('False')) True
True print(bool(-10.25))
print(bool('yes'))
True

DEPARTMENT OF MECHANICAL ENGINEERING


~ 38 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

print(bool(0.001)) print(bool(10.05+2j))
True True
print(bool(0.0)) print(bool(-10.25+1j))
False True
print(bool(0.001+0.1j))
If we pass complex type arguments
True
print(bool(1+1j))
print(bool(1+0j))
True
True

str() : We can use this method to convert other type values to str type

We can use this method to convert other type values to str type

print(str(10)) print(str(yes))
10 -------------------------------
print(str(10.58)) NameError
10.58 Traceback (most recent call last)
print(str(10.5+2j)) <ipython-input-11-16085fe22908>
(10.5+2j) in <module>()
print(str(True)) 5 print(str(False))
True 6 print(str(0b111))
print(str(False)) ----> 7 print(str(yes))
False NameError: name 'yes' is not
print(str(0b111)) defined
7

FUNDAMENTAL DATA TYPES vs IMMUTABILITY

➢ 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.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 39 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

WHY IMMUTABILITY?
➢ Who is responsible for creating an Object in Python?

Python Virtual Machine (PVM) is responsible for creating an object in Python.

➢ In Python if a new object is required, then PVM won’t create an object immediately.
First, it will check if any object is available with the required content or not.

➢ If available then the 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.

x = "Mechanical"
y = "Mechanical"
z = "Mechanical"
print(id(x))
print(id(y))
print(id(z))
140503971214064
140503971214064
140503971214064

➢ 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

DEPARTMENT OF MECHANICAL ENGINEERING


~ 40 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

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.

➢ In the last example, we have proved that all the reference variables are pointing to
single object, we are used id() function to compare their addresses.

➢ Instead of comparing the addresses, we can use a short-cut approach also. i.e.,
we can make use of is operator.

x = "Mechanical"
y = "mechanical"
print(x is y)
False
140503971214064
140503970840624
Immutability vs Mutability

Object reusability concept is not applicable for complex types.

Python generally pools integers between -5 to +256, in the pre-allocated object list. This
is also applicable for characters(str) after all ASCII codes are integers.

Note

Pooling is not applicable for float values.

ids are equal for integers ranging from -5 to + 256


a=-5 a=257
b=-5 b=257
print(id(a), id(b)) print(id(a), id(b))
94791108434240 94791108434240 140503971985872 140503971986800

DEPARTMENT OF MECHANICAL ENGINEERING


~ 41 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

COMPOSITE DATA TYPES


Composite types are a combination of primitive and other data types.

o list

o tuple

o set

o frozenset

o dictionary

LIST:

➢ List is a collection of items (Python objects) that are ordered and mutable.

➢ The purpose of the list is, to group up the things, which fall under the same category.

➢ Examples

❑ List of grocery items,

❑ List of employee ids,

❑ List of book names

❑ Names of all students

❑ Roll numbers of all students

❑ Mobile numbers of all students etc..,

➢ As a group of similar elements stored in a list, mostly those are homogeneous (of the
same data type). Creating a list in python is putting different comma-separated-
values, between square brackets ([ ]).

➢ Even though the list principle suggests homogeneous data items in it, it is not
mandatory and still allowed to have different types which make it the most powerful
tool in Python

➢ List allows duplicates

DEPARTMENT OF MECHANICAL ENGINEERING


~ 42 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

✓ Growable in nature, i.e based on our requirement we can increase or decrease the
size.

✓ Applications: If the content is keep on changing, better to opt for list type. For
example, Youtube comments or Facebook comments or Udemy reviews (which are
keep on changing day by day).

TUPLE:
➢ A tuple is a data type similar to a list.

➢ The major differences between the two are: Lists are enclosed in square
brackets [] and their elements and size can be changed (mutable), while tuples are
enclosed in parentheses () and their elements cannot be changed (immutable).

➢ Tuples can be thought of as read-only lists.

Note: Since a tuple is immutable, iterating through a tuple is faster than with a list. This
gives a slight performance improvement.

➢ Once a tuple is defined, we cannot add elements in it or remove elements from it.
A tuple can be converted into a list so that elements can be modified and converted
back to a tuple.

➢ A tuple is represented using parenthesis ( ). Sometimes parenthesis is optional.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 43 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

✓ Applications: If the content is fixed, better to opt for tuple type.

For example, In Banks, account type - Only 2 values are there, 1. Savings 2. Current

At runtime account types never going to change throughout Bank Project. So, to represent
bank account types, better to go for the tuple concept.

Some other Examples, Where allowed inputs are fixed (Best suitable type is tuple):
1. Vendor machines (Only accept 2/-,5/- coins only)

2. In the Metro stations also, If you want to get the tickets, you have to insert either 10/-
note or 20/- note only

Difference between List and Tuple

List Tuple
Mutable Immutable
Dynamically resizable array Fixed in size
To store list elements python virtual To store tuple elements python virtual memory
memory requires more memory requires less memory.
Emphasizes on quantity Emphasizes on structure
Unhashable Hashable
Use square brackets Use parenthesis (Optional sometimes)
Comma not required when having a single
Comma is required when having a single element
element
Tuple elements can access within less time,
Performance is less compared to tuple.
because they are fixed (performance is more)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 44 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

SET:

➢ A set is a mutable data type and We can add or remove items / elements from it.

➢ The set data type is, as the name implies, a mathematical set.

➢ Set does not allow duplicates. Set does not maintain order. This is because the
placement of each value in the set is decided by an arbitrary index produced by the
hash() function. So, we should not rely on the order of set elements, even though
sometimes it looks like order.

➢ Internally uses a hash table. Values are translated to indices of the hash table using
the hash() function. When a collision occurs in the hash table, it ignores the element.
This explains, why sets unlike lists and tuples can't have multiple occurrences of the
same element. type() of set is 'set'.

➢ index concept is not applicable

➢ A set is represented with { }.

Note : Mutable data types like list, set and dictionary cannot become elements of a set.

➢ The main uses of sets are:

➢ Membership testing

➢ Removing duplicates from a sequence

➢ Performing mathematical operations such as intersection, union, difference,


and symmetric difference

➢ For example, we want to send one SMS to all the students of a class. In this
duplicate numbers are not allowed and in any order, we can send SMS. At
last, all the students should receive the message. if you have such type of
requirement, then it is better to go for the set data type.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 45 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

What is the difference between set and list data types?


➢ In the list, the order is preserved, but in set order is not preserved.

➢ Duplicate elements are allowed in the list, but duplicate elements are not allowed in
the set.

➢ List can be represented by using square brackets and set can be represented by using
curly braces.

FROZENSET(): IS IMMUTABLE

➢ The frozenset() is an inbuilt function in Python which takes an iterable object as input
and makes them immutable. Simply it freezes the iterable objects and makes them
unchangeable.

➢ In Python, frozenset is same as set except its elements are immutable. This function
takes input as any iterable object and converts them into immutable object. The order
of element is not guaranteed to be preserved.

➢ In general, meaning of frozen is freezing, i.e, No one going to change, can't move,
fixed etc.,

➢ Frozen set is exactly same as set except that it is immutable. Hence we cannot use
add or remove functions

# Python program to understand frozenset() function


# tuple of numbers
nu = (1, 2, 3, 4, 5, 6, 7, 8, 9)
# converting tuple to frozenset
fnum = frozenset(nu)
# printing details
print("frozenset Object is : ", fnum)
Output:frozenset Object is : frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9})

we cannot use add or remove functions

DEPARTMENT OF MECHANICAL ENGINEERING


~ 46 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

What is the difference between Frozen set and tuple data types?
1. In tuple, order is preserved, but in frozen set order is not applicable.
2. In tuple duplicate elements are allowed, but in frozen set duplicates are not allowed.
3. Index, slice concepts are applicable, but in frozen set index,slice concepts are not
applicable.
Note : The only similarity between tuple and frozen set is, both are immutable.

DICTIONARY

➢ list l = [34, 32.5, 33, 35, 32, 35.1, 33.6]


tuple =(34, 32.5, 33, 35, 32, 35.1, 33.6)

➢ set ={34, 32.5, 33, 35, 32, 35.1, 33.6}

➢ forzen set frozenset=({34, 32.5, 33, 35, 32, 35.1, 33.6})

DEPARTMENT OF MECHANICAL ENGINEERING


~ 47 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

➢ If you observe this, all these data types are talks about a group of individual values.
Some times, If we want to represent a group of values as key-value pairs then we
should go for dict data type.

➢ Let's take a list l = [34, 32.5, 33, 35, 32, 35.1, 33.6]

➢ Suppose the above list l is representing the maximum temperatures of the last week,
from Sunday to Saturday. How do you access max temperature on Thursday?

➢ As Index 0 represents max temperature on Sunday and Index 1 represents Monday,


Index 2 represents Tuesday, and so on....

➢ Thus, print(l[4]) gives max temperature on Thursday.

➢ Associating temperatures and indices(numeric) in this way gives an unrealistic


perspective on the problem. If there is a way to access each temperature in the list
with meaningful indices like l['Sunday'], l['Monday'], etc... make associations more
lively, problem-solving, and more realistic. This is where the dictionary can really help
us.

➢ Dictionary is an associative container, which has a set of Key-Value pairs. 'Key' is the
'Index', through which we access associated value.

➢ d = {'Sunday' : 34, 'Monday' : 32.5, 'Tuesday' : 33, 'Wednesday' : 35, 'Thursday'


: 32, 'Friday' : 35.1, 'Saturday' : 33.6}

➢ Representation: dict= {key1 : value1, key2 : value2, key3 : value3,………….}

Dictionary is an unordered data structure and it is a collection of key and value pairs.

General usage of dictionaries is to store key-value pairs like :

➢ Employees and their wages

➢ Countries and their capitals

➢ Commodities and their prices

➢ Students roll numbers and their names

➢ Mobile numbers and their address

In a dictionary, the keys should be unique, but the values can change. For example,
the price of a commodity may change over time, but its name will not change.
Immutable data types like number, string, tuple etc. are used for the key and any data

DEPARTMENT OF MECHANICAL ENGINEERING


~ 48 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

type is used for the value.


Dictionaries are represented using key-value pairs separated by commas inside curly
braces {}. The key-value pairs are represented as key : value. For example, daily
temperatures in major cities are mapped into a dictionary as

{ "Hyderabad" : 27 , "Chennai" : 32 , "Mumbai" : 40 }.

Binary Types
Binary data types are the types made-up of bytes.

▪ bytes

▪ bytearray

▪ Memoryview

We can see, how binary types look like.

b = b"Apple" # bytes
print("b: ", type(b))
ba = bytearray(5) # bytearray
print("ba: ", type(ba))
mv = memoryview(b"2") # memory view
print("mv: ", type(mv))
b: <class 'bytes'>
ba: <class 'bytearray'>
mv: <class 'memoryview'>

DEPARTMENT OF MECHANICAL ENGINEERING


~ 49 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

bytes Data Type: it is not much frequently used data type in python

▪ bytes data type represents a group of byte numbers just like an array.

▪ Eg:
x = [10,20,30,40]
b = bytes(x)
type(b)==>bytes
print(b[0])==> 10
print(b[-1])==> 40
>>> for i in b : print(i)
10
20
30
40

▪ Conclusion 1:
The only allowed values for byte data type are 0 to 256. By mistake if 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.
Eg:
>>> x=[10,20,30,40]
>>> b=bytes(x)>>> b[0]=100

TypeError: 'bytes' object does not support item assignment


bytearray Data type:
• If we want to handle binary data like video files and audio files, we need to make
use of byte and bytearrary data types
bytearray is exactly same as bytes data type except that its elements can be
modified.
Eg 1:
x=[10,20,30,40]
b = bytearray(x)
for i in b : print(i)
10

DEPARTMENT OF MECHANICAL ENGINEERING


~ 50 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

20
30
40
b[0]=100
for i in b: print(i)
100
20
30
40
Eg 2:
>>> x =[10,256]
>>> b = bytearray(x)
ValueError: byte must be in range(0, 256)

Memory view
memoryview objects allow Python code to access the internal data of an object that
supports the buffer protocol without copying. The memoryview() function allows direct
read and write access to an object’s byte-oriented data without needing to copy it first.

Syntax: memoryview(obj)
byte_array = bytearray('XYZ', 'utf-8')
mv = memoryview(byte_array)
print(mv[0])
print(bytes(mv[0:1]))
Output:
88
b'X

OPERATORS:

What is an Operator?
Operators are symbols, such as +, –, =, >, and <, that perform (action on operands) certain
mathematical or logical operation to manipulate data values and produce a result based
on some rules.

An operator manipulates the data values called operands.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 51 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

x+y

In the above expression, + is the operator, x and y are operands.

• Types:
➢ Arithmetic Operators

➢ Comparison (Relational) operators

➢ Assignment operators

➢ Logical operators

➢ Bitwise operators

➢ Shift operators

➢ Ternary operator

➢ Membership operators

➢ Identity operators

DEPARTMENT OF MECHANICAL ENGINEERING


~ 52 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Arithmetic operators
Arithmetic operators are used to perform common mathematical operations or arithmetic
operations.

Operator Operation Description Expression and its result

+ Addition Adds values on either side of 10 + 20 = 30


the operator.

- Subtraction Subtracts right hand operand 20 - 10 = 10


from left hand operand.

* Multiplication Multiplies values on either 11 * 11 = 121


side of the operator

/ Division Divides left hand operand by 23 / 2 = 11.5


right hand operand

** Exponent Performs exponential (power) 2 ** 3 = 8


calculation on operators

% Modulus Divides left hand operand by 12 % 5 = 2


right hand operand and
returns remainder

// Floor division Floor Division - The division of 23 // 2 = 11 (Integer division)


(Integer the operands where the result 9.0 // 2.0 = 4.0
division) is the quotient in which the -11 // 3 = -4
digits after the decimal point -11.0 // 3 = -4.0
are removed. But if one of the
operands is negative, the
result is floored, i.e., rounded
away from zero (towards
negative infinity).

DEPARTMENT OF MECHANICAL ENGINEERING


~ 53 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Note: For any number x, x/0 and x%0 always raises "ZeroDivisionError"
10/0
10.0/0
// - Integer Division
print(7 / 2) # Division
print(7 // 2) # Integer or Floor Division
print(7 // 2.0) # Integer or Floor Division
print(7.0 // 2) # Integer or Floor Division
print(7.0 // 2.0) # Integer or Floor Division
3.5
3
3.0
3.0
3.0

print(math.ceil(10.3))

Output:11

DEPARTMENT OF MECHANICAL ENGINEERING


~ 54 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Example-1

Write a program to read two int inputs from the user and display the results of the
arithmetic operations:

num1 = int(input("Enter num1: "))


num2 = int(input("Enter num2: "))
print('{0} + {1} = {2}'.format(num1, num2,num1+num2))
print('{0} - {1} = {2}'.format(num1, num2,num1-num2))
print('{0} * {1} = {2}'.format(num1, num2,num1*num2))
print('{0} / {1} = {2}'.format(num1, num2,num1/num2))
print('{0} ** {1} = {2}'.format(num1, num2,num1**num2))
print('{0} % {1} = {2}'.format(num1, num2,num1%num2))
print('{0} // {1} = {2}'.format(num1, num2,num1//num2))

Example1: Anotherway of writing program

#Arithmetic Operators are +, -, *, /, **, %, //


num1 = int(input("Enter num1: "))
num2 = int(input("Enter num2: "))
print("{} + {} = {}".format(num1,num2,num1+num2))# print num1+num2
print("{} - {} = {}".format(num1,num2,num1-num2))# print num1-num2
print("{} * {} = {}".format(num1,num2,num1*num2))# print num1*num2
print("{} / {} = {}".format(num1,num2,num1/num2))# print num1/num2
print("{} ** {} = {}".format(num1,num2,num1**num2))# print num1**num2
print("{} % {} = {}".format(num1,num2,num1%num2))# print num1%num2
print("{} // {} = {}".format(num1,num2,num1//num2))# print num1//num2

DEPARTMENT OF MECHANICAL ENGINEERING


~ 55 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

What is eval () in python and what is its syntax?


Answer: eval is a built-in- function used in python, eval function parses the expression
argument and evaluates it as a python expression. In simple words, the eval function
evaluates the “String” like a python expression and returns the result as an integer.

input = input("Enter any number of your choice:")


print(input)
print(type(input))
--------------------------------------------------------------------
Enter any number of your choice: 10 + 10
10 + 10
<class 'str'>
See like I said I entered an integer 10+ 10 where I was expecting a
result of 20 (10 + 10) but the input method returned a string of the same
input entered.
eval = eval(input("Enter any number of your choice"))
print(eval)
print(type(eval))
--------------------------------------------------------------------
Enter any number of your choice: 10 + 10
20
<class 'int'>
Write a program to find quotient and remainder of the given two values using
divmod()
• The divmod(dividend,divisor) function returns a tuple containing the
quotient and the remainder when argument1 (dividend) is divided by
argument2 (divisor).
• The syntax of the divmod() function is :
• divmod(x, y)
• x - a non-complex number (numerator)
• y - a non-complex number (denominator)
• Note: If the second argument is 0, it returns Zero Division Error
• Note: If the first argument is 0, it returns (0, 0)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 56 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Ex: 5 Write a program to find quotient and remainder of the given two
values using divmod()

num1 = int(input("Enter number-1: "))


num2 = int(input("Enter number-2: "))
x = divmod(num1, num2)
print("{} // {} = {}" .format(num1, num2, x[0]))
print("{} % {} = {}" .format(num1, num2, x[1]))

Output:
For example, if the user gives the input as:
Enter number-1: 12
Enter number-2: 4
Sample Input and Output:
Enter number-1: 45
Enter number-2: 3
45 // 3 = 15
45 % 3 = 0

Arithmetic Operators with bool type


Internally Boolean values are represented as integer values only

print('Mechanical' * True) #True => 1

print('Mechanical' * False) #False => 0, output is an empty string

Comparison (Relational) Operators - An overview


Relational operators are used to comparing the values of two operands and they produce
Boolean values (True or False) only

The operands can be Numbers or Strings or Boolean values. Strings are compared letter
by letter using their ASCII values, thus, “P” is less than “Q”, and “Aston” is greater than
“Asher”.

Equal to (==) & Not Equal to ( !=) are called Equality operators and the remaining are
relational operators.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 57 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Operator Operation Description Expression and its


result

== Equal to If the values of two operands 23 == 34 (False)


are equal, then the condition 10 == 10 (True)
becomes True.

!= Not equal to If the values of two operands 23 != 34 (True)


are not equal, then the 10 != 10 (False)
condition becomes True.

< If value of left operand is less 10 < 20 (True)


than value of right operand, 20 < 5 (False)
Less than
then condition becomes true.

> If value of left operand is 10 > 20 (False)


greater than value of right 20 > 5 (True)
Greater than
operand, then condition
becomes true.

<= Less than or If value of left operand is less 10 <= 20 (True)


equal to than or equal to value of right 20 <= 20 (True)
operand, then condition
becomes true.

>= Greater than or If value of left operand is 10 >= 20 (False)


equal to greater than or equal to of 20 >= 20 (True)
right operand, then condition
becomes true.

Equality Operators:
Equality operators are used to check whether the given two values are equal or not. The
following are the equality operators used in Python.
1. Equal to (==)
2. Not Equal to (!=)
print(10==20)
print(10!=20)
False
True
print(1==True)
print(10==10.0)
print(‘Mechanical'==‘Mechanical')
True
True
True

DEPARTMENT OF MECHANICAL ENGINEERING


~ 58 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

We can apply these operators for any type even for incompatible types also.
print(10==‘Mechanical')
False
print(10=='10')
False
Note:
The Chaining concept is applicable for equality operators.

If at least one comparison returns False then the result is False. Otherwise, the result is
True.

print(10==20==30==40)
print(10==10==10==10)

False
True

Example-1: Relational operators for number types

num1 = int(input("Enter num1: "))


num2 = int(input("Enter num2: "))
z = num1 > num2
print("Is {} greater than {} = {}".format(num1, num2, z))
z = num1 < num2
print("Is {} less than {} = {}".format(num1, num2, z))
z = num1 == num2
print("Is {} equal to {} = {}".format(num1, num2, z))
z = num1 != num2
print("Is {} not equal to {} = {}".format(num1, num2, z))
z = num1 >= num2
print("Is {} greater than or equal to {} = {}".format(num1, num2, z))
z = num1 <= num2
print("Is {} less than or equal to {} = {}".format(num1, num2, z))

Comparison operators-strings
• All the comparison operators work on strings also. The result is either True or False.

• Python compares strings using the Unicode value of the characters (lexicographical).

DEPARTMENT OF MECHANICAL ENGINEERING


~ 59 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

• The comparison is made by taking the ordinal values of each character in the string
and comparing it with the ordinal values of the character at the same position in the
other string.

• If the ordinal value of the character in the first string is greater than the ordinal value
of the character in the second string, then the comparison stops and the first string is
declared greater than the second string. The length of the string does not matter.

• In Python, the ordinal value of a character can be found using the ord() function, which
takes the character as an argument.

print(ord('P'))➔80

print(ord('Q')) ➔81

print(chr(97)) ➔a

print(chr(65)) ➔A

Example-2: Relational operators for string types

Write a program to understand the use of comparison operators using conditional


parameters. Take input from user using input() method.

During execution, the program should print the message on the console as:

Enter first string:

Enter second string:

For example, if the user gives the input as:

Enter first string: Rebecca

Enter second string: Bethany

Sample Input and Output

str1 is: Rebecca

str2 is: Bethany

Is Rebecca greater than Bethany = True

Is Rebecca less than Bethany = False

Is Rebecca equal to Bethany = False

Is Rebecca not equal to Bethany = True

DEPARTMENT OF MECHANICAL ENGINEERING


~ 60 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Is Rebecca greater than or equal to Bethany = True

Is Rebecca less than or equal to Bethany = False

We can apply relational operators even for Boolean types also

print(True > False)


print(True >= False) # True ==> 1
print(True < False) # False ==> 0
print(True <= False)
Output:
True
True
False
False
print(10 > ‘Mechanical')
Output:

DEPARTMENT OF MECHANICAL ENGINEERING


~ 61 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Traceback (most recent call last):


File "C:\Users\bsrrg\OneDrive\Desktop\practice
programs\Untitled2.py", line 1, in <module>
print(10>'Mechancial')
TypeError: '>' not supported between instances of 'int' and 'str'

Chaining of relational operators:


• Chaining relational operators is possible.

• In the chaining, if all comparisons return True then the only result is True.

• If at least one comparison returns False then the result is False

print(10<20) # ==>True
print(10<20<30) # ==>True
print(10<20<30<40) # ==>True
print(10<20<30<40>50) # =>False

Assignment operators
Assignment Operators are used to assigning values to variables.
Operator Description Expression and its result

Simple assignment Operators


= Assigns values from right side operands to left c = a + b assigns value of a + b
side operand into c
Compound Assignment operators (combine assignment operator with some other operator )

+= Adds right operand to the left operand and c += a, equivalent to c = c + a


assign the result to left operand
-= Subtracts right operand from the left operand c -= a, equivalent to c = c - a
and assign the result to left operand
*= Multiplies right operand with the left and assign c *= a, equivalent to c = c * a
the result to left operand
/= Divides left operand with the right and assign c /= a, equivalent to c = c / a
the result to left operand
**= Performs exponential calculation on left and c **= a, equivalent to c = c ** a
right operand and assign the result to left
operand
%= Performs modulo division of left and right c %= a, equivalent to c = c % a
operands and assign the result to left operand

//= Performs floor division on left and right c //= a, equivalent to c = c // a


operands and assign the result to left operand

DEPARTMENT OF MECHANICAL ENGINEERING


~ 62 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Ex:

x = int(input("Enter an integer value: "))


y = int(input("Enter a non zero integer value: "))
print("x = {}".format(x))
print("y = {}".format(y))
a = x
b = y
a_1 =x
a_2 =x
a_3 =x
a_4 =x
a_5 =x
a_6 =x
a+=b
print("After x += y : x = {} and y = {}".format(a, b))
a_1 -=b
print("After x -= y: x = {} and y = {}".format(a_1, b))
a_2 *=b
print("After x *= y: x = {} and y = {}".format(a_2, b))
a_3 /=b
print("After x /= y: x = {} and y = {}".format(a_3, b))
a_4**=b
print("After x **= y: x = {} and y = {}".format(a_4, b))
a_5 //=b
print("After x //= y: x = {} and y = {}".format(a_5, b))
a_6%=y
print("After x %= y: x = {} and y = {}".format(a_6, b))

Logical operators
Logical operators are used to combining multiple relational expressions into one.

A logical operator is derived from Boolean algebra where the result is either True or False.
It is generally used to represent logical comparison the way it is done in real life.

1 represents True and 0 represents False. (Internally 0 represents False and anything
else represents True)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 63 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

The logical operators supported in Python are similar to the logic gates and are as follows:

1. and - Logical AND: The result is True, only if both the operands are True. ( 1 and
1 is the only condition where the result is 1, any other combination results in 0.)
2. or - Logical OR: The result is True if any one of the operands is True. ( 0 and 0 is
the only condition where the result is 0, any other combination results in 1.)
3. not - Logical NOT: The result negates the operand, i.e if the operand is True, the
result is False and vice versa

For non-boolean types behavior:


Note :

0 means False

non-zero means True

empty strings, list, tuple, set, dict is always treated as False

DEPARTMENT OF MECHANICAL ENGINEERING


~ 64 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Ex:

userName = input('Enter User Name : ')


password = input('Enter Password : ')
if (userName == 'Mechanical' and password == 'Engineering'):
print('valid User')
else:
print('invalid user')

Ex:

Take two inputs from the user using input() function, one is gender of the person
either M or F in string format and another one is age of the person in integer format. Write
a simple program to see whether the given person is eligible for concession or not and
print the result as shown in the examples:

Follow these instructions to identify whether the person is eligible for the concession or
not.

If the person is male and age >=65, Eligible for concession.

If the person is female and age >= 60, Eligible for concession.

In all other cases, the person is not eligible for concession.

Sample Input and Output 1:

Please enter M(male) or F(female): F

Please enter Age: 70

Eligible for Concession

Sample Input and Output 2:

Please enter M(male) or F(female): M

Please enter Age: 63

Not Eligible for Concession

DEPARTMENT OF MECHANICAL ENGINEERING


~ 65 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Here, str is optional

Using Logical "or"


Write a program to understand the logical or operator. Take two integers a and b as inputs
from the console using input() function. The program should print True if either of the
inputs is 6 or their sum is 6 or difference is 6, Otherwise it should print False.

Sample Input and Output1:

Enter a: 59

Enter b: 6

True

Sample Input and Output2:

Enter a: 30

Enter b: 30

False

DEPARTMENT OF MECHANICAL ENGINEERING


~ 66 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Using Logical "not"


The logical not operator negates the Boolean operand given to it. E.g. not True is False.
Similarly, not(a and b) is the expression which indicates True, only when both a and b are
not True

Write a program to understand the logical not operator. The program should
print Weekend if the day is either SAT or SUN, otherwise it should print Not Weekend.
Take the input day from the user.

Sample Input and Output1:

Enter day: SAT

Weekend

Sample Input and Output2:

Enter day: MON

Not Weekend

Hint: Consider the days of the week are represented


as MON, TUE, WED, THU, FRI, SAT, SUN

DEPARTMENT OF MECHANICAL ENGINEERING


~ 67 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

X and Y for non-boolean type:

If x is x and y is

“truthy” y

“falsy” x

Here, X and Y are non-boolean types and the result may be either X or Y but not
boolean type (i.e., The result is always non-boolean type only).
if 'X' is evaluated to false then the result is 'X'.
If 'X' is evaluated to true then the result is 'Y'.

print(10 and 20)


print(0 and 20)
print('mechanical' and 'engineering')
print('' and 'mechanical') # first argument is empty string
print(' ' and ' mechanical ') # first argument contains space character,
so it is not empty
print(' mechanical ' and '') # second argument is empty string
print(' mechanical ' and ' ') # second argument contains space character,
so it is not empty
20
0

DEPARTMENT OF MECHANICAL ENGINEERING


~ 68 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

engineering

mechanical

not X:
Even you apply not operator for non boolean type, the result is always boolean type only.
If X is evaluates to False then result is True otherwise False

print(not 'Mechanical') #not True ➔False


print(not '') #not false ➔True
print(not 0) #not False ➔True
print(not 10) #not True ➔False
False
True
True
False

Bitwise operators
• Bitwise operators are used to perform bitwise calculations on integers.

• Bitwise operators are used to manipulating values at the bit and byte level.

• The integers are first converted into binary and then operations are performed on bit
by bit, hence the name bitwise operators.

• Then the result is returned in a decimal format which will be printed on the console or
shell.

• These operators are applicable only for int and boolean types. By mistake, if we are
trying to apply for any other type then we will get an Error.

Operator Operation Description Expression and its result

0 & 0 -> 0
0 & 1 -> 0
1 & 0 -> 0
Operator copies a bit to the
1 & 1 -> 1
& Bitwise AND result if it exists in both
Ex: x=0b1010
operands
y=0b1100
Print(bin(x&y)
‘0b1000’

DEPARTMENT OF MECHANICAL ENGINEERING


~ 69 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

0|0 -> 0 Ex: x=0b1010


It copies a bit if it exists in either 0|1 -> 1 y=0b1100
| Bitwise OR
operand. 1|0 -> 1 print(bin(x|y)
1|1 -> 1 ‘0b1110’

^ Bitwise XOR It copies the bit if it is set in 0^0 -> 0 Ex: x=0b1010
one operand but not both. 0^1 -> 1 Y=0b1100
1^0 -> 1 print(bin(x^y)
1^1 -> 0 ‘0b110’

~ Bitwise NOT It is unary and has the ~x is the x=20


effect of 'flipping' bits. same as -x- print(~x)
~ toggles ones to zeros, 1. -21
zeros to ones. This is
called as 1’s compliment.

Bitwise AND Bitwise OR Bitwise XOR and Assign Bitwise Left Bitwise Right Shift
and Assign and Assign Shift and and Assign:
Assign

a=3 a=3 a=3 a=3 a=3


b=5 b=5 b=5 b=5 b=5
#a=a&b #a=a|b #a=a^b # a = a << b # a = a >> b
a &= b a |= b a ^= b a <<= b a >>= b
# Output # Output
print(a) # Output # Output print(a) # Output
print(a) print(a) print(a)
Output Output Output Output Output
1 7 6 96 0

In Python, negative numbers are represented in 2's complement integer format. A 2's
compliment is (1's compliment + 1).

In 8-bit format, x = 20 is represented by x --> 0001 0100 which is equivalent to 20


x' (1's compliment of x) --> 1110 1011 which is equivalent to -21
x '' (2's compliment of x) --> 1110 1100 which is equivalent to -20
So x + x" is always 0.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 70 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Shift operators
Bit-wise Left Shift

x = 20
print (x << 3)
print(x)
160
20

In this example we are shifting bits of 20 (i.e 0b10100) 3 times to the left side, which
becomes 0b10100000 i.e.., Three 0s are added to the right side.

Note:

When x is shifted n times to the left side, its value becomes x * 2^n.

Bit-wise Right Shift


x = 160
print(x >> 3)
print (x)
20
160

In this example we are shifting bits of 160 (i.e 0b10100000) 3 times to the right side, which
becomes 0b10100. Three bits are discarded from right side.

Note:

When x is shifted n times to the right side, its value becomes x / 2^n.

Note: Bit-wise short-hand assignment operators

<<=, >>=, &=, |=, ^=

e.g, x <<= n is equivalent of x = x << n

DEPARTMENT OF MECHANICAL ENGINEERING


~ 71 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Ternary Operator or conditional operator


The ternary operator is a way of writing conditional statements in Python. As the name
ternary suggests, this Python operator consists of three operands.

The ternary operator can be thought of as a simplified, one-line version of the if-else
statement to test a condition.

Syntax

The three operands in a ternary operator include:

condition: A boolean expression that evaluates to either true or false.


true_val: A value to be assigned if the expression is evaluated to true.
false_val: A value to be assigned if the expression is evaluated to false.

Syntax: x = firstValue if condition else secondValue


If condition is True then firstValue will be considered else secondValue will be
considered.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 72 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Eg 1:
a, b=23,43 # a =23 b = 43
c = 50 if a>b else 100
print(c)
100
Eg 2: Read two integer numbers from the keyboard and print minimum value using
ternary operator
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
min=a if a<b else b
print("Minimum Value:",min)
Enter First Number:255
Enter Second Number:22
Minimum Value: 22

Syntax: x = firstValue if condition else secondValue


If condition is True then firstValue will be considered else secondValue will be
considered.
Eg 1:
a, b=23,43 # a =23 b = 43
c = 50 if a>b else 100
print(c)
100
Eg 2: Read two integer numbers from the keyboard and print minimum value using
ternary operator
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
min=a if a<b else b
print("Minimum Value:",min)
Enter First Number:255
Enter Second Number:22
Minimum Value: 22

DEPARTMENT OF MECHANICAL ENGINEERING


~ 73 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Nesting of ternary operator is possible.


Eg 3: Program for finding minimum of 3 numbers using nesting of ternary operators
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
c=int(input("Enter Third Number:"))
min= a if a<b and a<c else b if b<c else c
print("Minimum Value:",min)

Enter First Number:10


Enter Second Number:20
Enter Third Number:30
Minimum Value: 10

Program for finding maximum of 3 numbers

a=int(input("Enter First Number:"))


b=int(input("Enter Second Number:"))
c=int(input("Enter Third Number:"))
max=a if a>b and a>c else b if b>c else c
print("Maximum Value:",max)
Enter First Number:34
Enter Second Number:22
Enter Third Number:55
Maximum Value: 55

Membership Operator

Membership operators checks the membership of the item/sub-string in the


string/container.

The Right Hand Side (RHS) can be a String, List, Tuple, Set or a Dictionary.

For strings, the Left Hand Side (LHS) can be any string. If this string exists in the RHS
string, then True is returned. Otherwise False is returned.

For all other data types (Lists, Tuples, Sets, Dictionaries, etc.) the LHS should be a
single element.

For strings the LHS can be a string of any length.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 74 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Operator Description

in Returns true if value / variable found in the specified sequence and false otherwise.

not in Returns true if value / variable not found in the specified sequence and false
otherwise.

Ex:

x="hello learning Python is very easy!!!"


print('h' in x)
print('d' in x)
print('d' not in x)
print('python' in x) # case sensitivity
print('Python' in x)
True
False
True
False
True

Ex:2

list1=["sunny","bunny","chinny","pinny"]
print("sunny" in list1)
print("tunny" in list1)
print("tunny" not in list1)
True
False
True

Identity Operators - An overview


Identity Operators: Every object has an identity, a type, and a value. An object’s identity
never changes once it is created, you may think of it as the object’s address in memory.

The ‘is‘ operator compares the identity of two objects, the id() function returns an integer
representing its identity (currently implemented as its address).

id(object) : Returns the “identity” of an object. This is an integer that is guaranteed to be


unique and constant for this object during its lifetime.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 75 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Usually, this is the address of the object in memory.

If two integer or string variables have the same value, they point to the same memory
location.

But this is not true with floating-point numbers, lists, tuples, and dictionaries.

The identity operators in Python are "is" and "is not".

We can use identity operators for address comparison. There are two identity operators
used in Python:
i) is
ii) is not
r1 is r2 returns True if both r1 and r2 are pointing to the same object.
r1 is not r2 returns True if both r1 and r2 are not pointing to the same object

a=10
b=10
print(a is b)
True
x=True
y=True
print( x is y)
True

What is the Difference between '==' and 'is' operators?

• is Operator: 'is' operator meant for reference or address comparison.

When a is b returns true?

Ans: Whenever 'a' and 'b' pointing to the same object, then only 'a is b' returns true,
which is nothing but reference comparison (or) Address comparison.

Ex:

a=10
b=10
print(a is b)
print(id(a))
print(id(b))
True

DEPARTMENT OF MECHANICAL ENGINEERING


~ 76 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

2179289973264
2179289973264
• == Operator : ==' is meant for content comparison
Ex:
l1 = [10,20,30]
l2 = [10,20,30]
print(id(l1))
print(id(l2))
print(l1 is l2) # False
print(l1 == l2) # True
l3 = l1 # l3 is also pointing to l1
print(id(l3))
print(l1 is l3) # True
print(l1 == l3) # True

Precedence and Associativity

Operator precedence determines the way in which operators are parsed with respect to
each other.

Operators with higher precedence become the operands of operators with lower
precedence. Associativity determines the way in which operators of the same precedence
are parsed. Almost all the operators have left-to-right associativity. Operator precedence
is listed in TABLE. starting with the highest precedence to lowest precedence.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 77 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Python Program to Solve Quadratic Equation


# Solve the quadratic equation ax**2 + bx + c = 0
# import complex math module
import cmath
a = 1
b = 5
c = 6
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))
Output:
Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)

Python Program to Convert Celsius To Fahrenheit

# Python Program to convert temperature in celsius to fahrenheit


# change this value for a different result
celsius = 37.5
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit'
%(celsius,fahrenheit))

DEPARTMENT OF MECHANICAL ENGINEERING


~ 78 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

UNIT-II

Syllabus:
Input and Output statements: input() function, reading multiple values from the keyboard
in a single line, print() function, ‘sep’ and ‘end’ attributes, Printing formatted string,
replacement operator ({}). Control flow statements: Conditional statements. Iterative
statements. Transfer statements.

Strings: Operations on string, String slicing, important methods used on string.

Input ( ):
➢ input() function can be used to read data directly in our required format.

➢ In Python3, we have only the input() method and the raw_input() method (Python2)
is not available.

➢ Every input value is treated as str type only.

➢ Why does input() in Python 3 give priority to string type as return type?

Reason: The most commonly used type in any programming language is str type,
that's why they gave priority to str type as the default return type of input() function.

Ex1:
num1 = input("Enter num1: ")
num2 = input("Enter num2: ")
print('The sum of two numbers =', num1+num2)

output:
Enter num1: 15
Enter num2: 50
The sum of two numbers = 1550

Ex2:
num1 = int(input("Enter num1: "))
num2 = int(input("Enter num2: "))
print('The sum of Two numbers = ', num1+num2)

output:
Enter num1: 5
Enter num2: 6
The sum of Two numbers = 11

DEPARTMENT OF MECHANICAL ENGINEERING


~ 79 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Ex3:
num1 = float(input("Enter num1: "))
num2 = float(input("Enter num2: "))
print('The sum of two numbers =', num1+num2)

output:
Enter num1: 5.2
Enter num2: 3
The sum of two numbers = 8.2

We can write the code in single line also


print('The sum of Two numbers = ', int(input("Enter num1: "))+
int(input("Enter num2: ")))
Enter num1: 6
Enter num2: 8
The sum of Two numbers = 14

Program: Write a program to read Employee data from the keyboard and print that data.
Employee_Number = int(input("Enter Employee No:"))
Employee_Name = input("Enter Employee Name:")
Employee_salary = float(input("Enter Employee Salary:"))
Employee_address = input("Enter Employee Address:")
Employee_marital_status = bool(input("Employee Married or Not
Married:"))
print("Please Confirm your provided Information")
print("Employee No :",Employee_Number)
print("Employee Name :",Employee_Name)
print("Employee Salary :",Employee_salary)
print("Employee Address :",Employee_address)
print("Employee Married ? :", Employee_marital_status)

How to read multiple values from the keyboard in a single line:


a) Using split() function

b) Using input () function

c) Using map () function

d) Using List Comprehension

a) Using split() function


➢ This function helps in getting multiple inputs from users.

➢ This function generally breaks the given input by the specified separator and in case
the separator is not provided then any white space is considered as a separator.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 80 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

➢ This function is generally used to separate a given string into several substrings.
However, you can also use it for taking multiple inputs.

Syntax : input().split(separator, maxsplit)

➢ separator: This is a delimiter. The string splits at this specified separator. If it is not
provided then any white space is a separator.

➢ maxsplit: It is a number, which tells us to split the string into a maximum of provided
number of times. If it is not provided then the default is -1 which means there is no
limit.

i) Taking two inputs at a time:


a, b = input("Enter 2 variables: ").split()
print("a is: ",a)
print("b is: ",b)
Enter 2 variables: hi there
a is: hi
b is: there
Enter 2 variables: 34 56
a is: 34
b is: 56
Note: As you can see, the input given can be any: int, string, float, etc. We haven’t
mentioned the separator used hence whitespace is considered as default.

ii) Taking Inputs with Separator and Maxsplit defined

x, y, z = input("Enter variables: ").split(",",3)


print(x, y, z)
Enter variables: how,are,you
how are you
x, y, z = input("Enter variables: ").split(",")
print(x,y,z)
Enter variables: how,are,you
how are you
Note: Whether or not maxsplit was defined, the results were the same. For both the above
cases only 3 inputs (not more or less can be provided corresponding to defined variables!)

iii) Taking Unlimited Inputs:

x= input("Enter variables: ").split(",")


print(x)
Enter variables: how,are,you,dear
['how', 'are', 'you', 'dear’]

DEPARTMENT OF MECHANICAL ENGINEERING


~ 81 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

iv) Taking Multiple Inputs as List

Taking multiple inputs at a time and type casting using the list() function.

With Map Function:

Used Map Function (Optional) to convert the input into an integer.

x = list(map(int, input("Enter multiple value: ").split()))


print("List of students: ", x)
Enter multiple value: 67 90 89 54 12 34 09
List of students: [67, 90, 89, 54, 12, 34, 9]
For the above code, because of the use of the map integer function, our input can only be
integers

Without Map Function:

x = list(input("Enter multiple value: ").split())


print("List of students: ", x)
Enter multiple value: hey 78 amazing person 2021
List of students: ['hey', '78', 'amazing', 'person', '2021’]
Note: Here as we did not use any map function, the type of input can be any!

b) input ()
You can take multiple inputs in one single line by using the input function several times as
shown below.

#multiple inputs in Python using input


x, y = input("Enter First Name: "), input("Enter Last Name: ")
print("First Name is: ", x)
print("Second Name is: ", y)
Output:
Enter First Name: FACE
Enter Last Name: Prep
First Name is: FACE
Second Name is: Prep
c) map()

map() is another function that will help us take multiple inputs from the user. In general,
the syntax for the map function is the map (fun, iter). Here fun is the function to which the
map function passes each iterable.

Syntax for multiple input using map():

variable 1, variable 2, variable 3 = map(int,input().split())

DEPARTMENT OF MECHANICAL ENGINEERING


~ 82 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

An example to take integer input from the user.

#multiple inputs in Python using map


x, y = map(int, input("Enter two values: ").split())
print("First Number is: ", x)
print("Second Number is: ", y)
Output:
Enter two values: 7 1
First Number is: 7
Second Number is: 1

An example to take string input from the user.


#multiple inputs in Python using map
x, y = map(str, input("Enter your first and last name: ").split())
print("First Name is: ", x)
print("Second Name is: ", y)
d) List Comprehension

List data types also help in taking multiple inputs from the user at a time. The syntax for
creating a list and storing the input in it is

x, y=[x for x in input("Enter two values: ").split()]

List allows you to take multiple inputs of different data type at a time. The below example
will help you understand better.

#multiple inputs in Python using list comprehension

x, y = [x for x in input("Enter your name and age: ").split(",")]


print("Your name is: ", x)
print("Your age is: ", y)
Output:
Enter your name and age: FACE Prep, 8
Your name is: FACE Prep
Your age is: 8
Explanation :

Here, we are using only one input function (i.e., input("Enter Your name and age:")). So
whatever you provide is treated as only one string.

Suppose, you are providing input as Face Prep, 20, this is treated as a single string.

If you want to split that string into multiple values, then we are required to use the split()
function.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 83 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

If we want to split the given string (i.e., Face Prep 20) with respect to space, then the code
will be as follows:

input(("Enter Your name and age:").split()

Here, we are passing an argument comma to split() function,

Now this single string(i.e., Face Prep, 20) is splitted into a list of two string values.

This concept is known as a list comprehension.

x,y = [x for x in input(("Enter Your name and age: ").split()] ===> it assigns Face Prep to x
and 20 to y. This concept is called list unpacking.

2 Inputs at a Time:

x,y = [int(x) for x in input("Enter 2 values: ").split()]


print("x is ",x)
print("y is",y)
Enter 2 values: 6 78
x is 6
y is 78
x,y = [int(x) for x in input().split()]
print("x is ",x)
print("y is",y)
78 90
x is 78
y is 90
Taking Multiple Inputs at a time:

x = [int(x) for x in input().split()]


print("Number of list is: ", x)
43 12 34 67 09 653 2321 12
Number of list is: [43, 12, 34, 67, 9, 653, 2321, 12]
Taking User-Defined Number of Inputs:

#Inputs of Number of inputs user want to enter:


n = int(input())
# defining empy list:
L= []
# Taking multiple inputs based on n:
for i in range(n):
t = input().split()
print(t)
The result for the above code would be a list with n number of user inputs.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 84 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Multiple Input Using Separator

x = [int(x) for x in input().split(",")]


print("Number of list is: ", x)
67,432,11,1,2,3,4
Number of list is: [67, 432, 11, 1, 2, 3, 4]
List Comprehension: Programs

Write a program to find square of odd numbers from range 1 to 20


odd_square = [x ** 2 for x in range(1, 21) if x % 2 == 1]
print(odd_square)
Output: [1, 9, 25, 49, 81, 121, 169, 225, 289, 361]

Write a program to find square of even numbers from range 1 to 20.


even_square = [x ** 2 for x in range(1, 21) if x % 2 == 0]
print(even_square)
Output: [4, 16, 36, 64, 100, 144, 196, 256, 324, 400]

Write a program to find power of 2 from 1 to 10


square = [x ** 2 for x in range(1, 11)] print(square)
Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

eval():
eval() Function is a single function that is the replacement of all the typecasting functions
in Python.

If you provide an expression as a string type, eval Function take a String and evaluate the
Result.

Eg:
x = eval('10+20+30')
print(x)
Output: 60
Eg:
x = eval(input('Enter Expression'))
Enter Expression: 10+2*3/4
Output: 11.5
Output function: print()
We can use print() function to display output to the console for end user sake.

Multiple forms are there related to print() function.

Form-1:print() without any argument


Just it prints new line character (i.e.,\n)
Ex1:

DEPARTMENT OF MECHANICAL ENGINEERING


~ 85 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

print("Mechanical Engineering")
print("RGMCET: ")
Output:
Mechanical Engineering
RGMCET
Ex2:
print("Mechanical Engineering")
print()
print("RGMCET")
Output:
Mechanical Engineering

RGMCET

Form-2: print() function to print of string argument


print("Mechanical Engineering")
Output: Mechanical Engineering

We can use escape characters also


print("Mechanical\nEngineering")
Mechanical
Engineering
print("Mechanical\tEngineering")
Mechanical Engineering

We can use repetition operator (*) in the string.


print("Mechanical Engineering"*2)
print('RGMCET'*2)
Mechanical EngineeringMechanical Engineering
RGMCETRGMCET
We can use + operator also
print('Mechanical'+'Engineering')
MechanicalEngineering
Note:
If both arguments are string type then + operator acts as concatenation operator.
If one argument is string type and second is any other type like int then we will get Error
If both arguments are number type then + operator acts as arithmetic addition operator.

**Form-3: print() with variable number of arguments:**

a, b, c = 10,20, 30
print("The values are: ", a, b, c)
The values are: 10 20 30

DEPARTMENT OF MECHANICAL ENGINEERING


~ 86 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Form-4: print() with 'sep' attribute: sep' attribute:


By default output values are separated by space. If we want we can specify a separator
by using the "sep" attribute

'sep' means separator.


Ex1:
a, b, c = 10,20, 30
print("The values are: ", a, b, c)
The values are: 10 20 30
print("The values are: ", a, b, c, sep = '')
The values are: 102030
print("The values are: ", a, b, c, sep = ' ')
The values are: 10 20 30

Ex2:
print("The values are: ", a, b, c, sep = ',')
The values are: ,10,20,30

print("The values are: ", a, b, c, sep = ':')


The values are: :10:20:30

print("The values are: ", a, b, c, sep = '-')


The values are: -10-20-30

Form-5: print() with 'end' attribute:


print("Mechanical")
print("Engineering")
Mechanical
Engineering
default value of 'end' attribute is newline character. (That means, if there is no end
attribute, automatically newline character will be printed)

If we want to output in the same line with space, we need to use the end attribute.

print("Mechanical", end = ' ')


print("Engineering")

Eg: Program to demonstrate both 'sep' and 'end' attributes.


print(10, 20, 30, sep = ':', end = '**') # output:
10:20:30**Engineering
print("Engineering")
print("Mechanical" + "Engineering") # Concatanation
MechanicalEngineering

DEPARTMENT OF MECHANICAL ENGINEERING


~ 87 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

print("Mechanical", "Engineering") #',' means space is the separator


Mechanical Engineering

Form-6: print(object) statement:


➢ We can pass any object (like list,tuple,set etc)as argument to the print() statement.
Syntax : print(objects)

➢ Here, objects are the values to be printed.

➢ We can use commas to print multiple variables / values at a time as shown below.

x = "Apple"
y = 10
z = 21.5
print(x, y, z)
Apple 10 21.5
Ex:

list=[1,2,3,4,5]
tuple=(1,2,3,4,5)
set={"mech", 'engg'}
dict={"Mech":1995, "dept":2022}
print(list)
print(tuple)
print(set)
print(dict)
Form-7: print(String, variable list):

We can use print() statement with String and any number of arguments.

Ex:
a = 'Mechanical'
b = 'students'
c = 'python programming class'
print("Hello", a, "Engineering", b)
print("welcome", 'to',c)
Hello Mechanical Engineering students
welcome to python programming class

Form-8: print(formatted string):

Syntax: print("formatted string" %(variable list))

DEPARTMENT OF MECHANICAL ENGINEERING


~ 88 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

• %i====>int
• %d====>int
• %f=====>float
• %s======>String type
Ex:
a=10
b=20.5
c=30.3
s= "Hello Dear"
l=[10, 20, 50, 60]
print("a value is %i" %a)
print("b value is %f and c value is %f" %(b,c))
print("Hi %s....your items:%s" %(s,l))
output:
a value is 10
b value is 20.500000 and c value is 30.300000
Hi Hello Dear....your items:[10, 20, 50, 60]

Form-9: print() with replacement operator {}


x = -100
y = 300
z = x + y

# normal way old style of printing


print(x, "plus", y, "is", z, "and", x, "is -ve")
# using format
print("{} plus {} is {} and {} is -ve".format(x, y, z, x))
print("{0} plus {1} is {2} and {0} is -ve".format(x, y, z))

# using f-string
print(f'{x} plus {y} is {z} and {x} is -ve')
Ex:
a,b,c,d = 10,20,30,40 # print a=10,b=20,c=30,d=40
print('a = {},b = {},c = {},d = {}'.format(a,b,c,d))

FLOW CONTROL STATEMENTS: INTRODUCTION


➢ By default, statements in a program are executed sequentially.

While executing the code,

▪ We may require to skip the execution of some statements,

▪ We may want to execute two or more blocks of statements exclusively,

DEPARTMENT OF MECHANICAL ENGINEERING


~ 89 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

▪ We may need to execute a block of statements repeatedly,

▪ We may need to direct the program's flow to another part of your program
without evaluating conditions.

➢ In such cases, control structures become handy. Control structures are mainly used
to control the flow of execution. They are used for decision making which means we
execute code only if certain criteria is matching.

Conditional Statements (or) Selection Statements


➢ 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 are always evaluated to be either True or False.

The following are the types of conditional statements.

➢ if statement

➢ if-else

➢ if-elif-else

➢ nested if-else

DEPARTMENT OF MECHANICAL ENGINEERING


~ 90 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

if Statement (One-way):

' if ' statement is used to decide whether a certain statement(s) have to be executed or
not.

Syntax:

if condition:

statements

What does the colon ':' operator do in Python?

▪ The : symbol is also used to start an indent suite of statements in case of if,
while, for, def and class statements

▪ As slice operator with a sequence:

The : operator slices a part from a sequence object such as list, tuple or string. Ex: >>>
a=[1,2,3,4,5]
>>> a[1:3]
[2, 3]

INDENTATION:

▪ Python identifies code-blocks using indentation.

▪ All the statements which need to be executed when the condition is True, should be
placed after 'if condition:' preceded by one tab(generally 4 spaces).

▪ All the statements after 'if' statement with one tab indentation, are considered as if
block

DEPARTMENT OF MECHANICAL ENGINEERING


~ 91 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Ex:

number = int(input("Enter a number"))


if number >= 0:
print("The number entered by the user is a positive number")
print("The number entered by the user is a neither zero nor a positive number")

In the above example, if the number is positive or zero then only 'if' block will get executed

Ex:

name = input("Enter name: ")


if name == "Mechanical":
print("Welcome to Mechanical Engineering")
print("Hi")

Program on if statement

#Program to illustrate simple if statement


num = int(input("Enter a number: "))
if (num % 3 == 0):
print('Given number {} is divisible by 3'.format(num))
print("End of program")

if-else
When we want to execute two blocks of code exclusively, we use the 'if-else' statement.
Only one block of code will be executed all the time.

Syntax:

if condition:
statements
else:
statements

DEPARTMENT OF MECHANICAL ENGINEERING


~ 92 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Ex:

name = input("Enter name: ")


if name == "Mechanical":
print("Hello Good Morning to Mechanical Engineering")
else :
print("Hi students")
print("How are You")

Program 1:

Find the greatest number between two given numbers.

num1 = int(input("Enter a number: "))


num2 = int(input("Enter a number: "))
if num1 > num2:
print("num1 is greater than num2")
else:
print("num2 is greater than num1")
print("The End")
Enter a number: 12
Enter a number: 35
num2 is greater than num1
The End
Ex:

Python Program to Check Whether a String is Palindrome or Not

# Program to check if a string is palindrome or not


my_str = 'aIbohPhoBiA'
# make it suitable for caseless comparison
my_str = my_str.casefold()
# reverse the string
rev_str = reversed(my_str)

# check if the string is equal to its reverse


if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
output:
The string is a palindrome.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 93 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Another way:

def isPalindrome(s):
return s == s[::-1]
# Driver code
s = "malayalam"
ans = isPalindrome(s)

if ans:
print("Yes")
else:
print("No")
output:
Yes

if-elif-else Statement:
When we have multiple exclusive cases, we use 'if-elif ladder'. Only one block of code will
be executed at any time.

Syntax:

if condition:
statements
elif condition:
statements

DEPARTMENT OF MECHANICAL ENGINEERING


~ 94 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

elif condition:
statements
.
.
.
else:
statements
Ex: Program to print the greatest number among three numbers.

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
print("The largest number is", largest)
Enter first number: 23
Enter second number: 14
Enter third number: 25
The largest number is 25.0

Ex:
# Python program to check if year is a leap year or not

year = 2000

# To get year (integer input) from the user


# year = int(input("Enter a year: "))

# divided by 100 means century year (ending with 00)


# century year divided by 400 is leap year
if (year % 400 == 0) and (year % 100 == 0):
print("{0} is a leap year".format(year))

# not divided by 100 means not a century year


# year divided by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
print("{0} is a leap year".format(year))

# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year

DEPARTMENT OF MECHANICAL ENGINEERING


~ 95 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

else:
print("{0} is not a leap year".format(year))
Output:
2000 is a leap year

Ex:
Program to print the grade assigned to the obtained marks.

score = float(input("Enter Score :"))


if score >= 90.0:
print("grade = 'A'")
elif score >= 80.0:
print("grade = 'B'")
elif score >= 70.0:
print("grade = 'C'")
elif score >= 60.0:
print("grade = 'D'")
else:
print("grade = 'F'")
output:
Enter Score :60
grade = 'D'

Looping (while, while-else)


➢ In Python, iterative statements allow us to execute a block of code repeatedly as
long as the condition is True. We also call it a loop statements.

➢ Python provides us the following two loop statements to perform some actions
repeatedly

▪ for loop

▪ while loop

DEPARTMENT OF MECHANICAL ENGINEERING


~ 96 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

for loop (fixed number of times):

• In the syntax, i is the iterating variable, and the range specifies how many times
the loop should run. For example, if a list contains 10 numbers then for loop will
execute 10 times to print each number.

• In each iteration of the loop, the variable i get the current value.

Why use for loop?

• Definite Iteration: When we know how many times we wanted to run a loop, then we
use count-controlled loops such as for loops. It is also known as definite iteration.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 97 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

For example, Calculate the percentage of 50 students. here we know we need to


iterate a loop 50 times (1 iteration for each student).

• Reduces the code’s complexity: Loop repeats a specific block of code a fixed
number of times. It reduces the repetition of lines of code, thus reducing the
complexity of the code. Using for loops and while loops we can automate and repeat
tasks in an efficient manner.

• Loop through sequences: used for iterating over lists, strings, tuples, dictionaries,
etc., and perform various operations on it, based on the conditions specified by the
user.

Ex:
To display numbers from 0 to 5
for num in range(0,6):
print(num)
output:
0
1
2
3
4
5
Ex:
numbers = [1, 10, 20, 30, 40, 50]
sum = 0
# Find sum of all the numbers using for loop
for i in numbers:
sum = sum + i
print ("The sum of numbers is", sum) # print sum here
colors = ['red', 'orange', 'green', 'yellow', 'white', 'violet']
for i in colors:
print(i)
# Similarly ierate over the given colors and print the colors
Ex:
To display odd numbers from 0 to 10
for num in range(0,10):
if num%2 !=0:
print(num)
1
3
5
7
9

DEPARTMENT OF MECHANICAL ENGINEERING


~ 98 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Ex:
To display even numbers from 0 to 10
for num in range(0,10):
if num%2 ==0:
print(num)
0
2
4
6
8
Ex:
To display numbers from 5 to 1 in descending order.
for num in range(5,0,-1):
print(num)
5
4
3
2
1
Ex: Write a Program to print characters present in the given string

str = "MECHANICAL"
for x in str:
print(x)
M
E
C
H
A
N
I
C
A
L
Example: Calculate the average of list of numbers
numbers = [10, 20, 30, 40, 50] #numbers = eval(input("Enter list"))
# definite iteration
# run loop 5 times because list contains 5 items
sum = 0
for i in numbers:
sum = sum + i
list_size = len(numbers)
average = sum / list_size
print("Sum of List of numbers: ", sum)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 99 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

print("Average of List of numbers: ", average)

output:
Sum of List of numbers: 150
Average of List of numbers: 30.0

# Reversed numbers using reversed() function


list1 = [10, 20, 30, 40]
for num in reversed(list1):
print(num)
Or
numbers = [1, 2, 3, 4]
for i in numbers[::-1]:
print(i)

# Iterating over a tuple


print("\nTuple Iteration")
t = ( "Programming", "is", "fun" )
for i in t:
print(i)

# Iterating over a dictionary


print("\nDictionary Iteration")
d = {"a" : 1, "b" : 2, "c" : 3}
for i in d:
print(i, d[i])
print("\nThe End")

Ex:
# Python program to find the factorial of a number provided by the user.

# change the value for a different result


num = 7

# To take input from the user


#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")

DEPARTMENT OF MECHANICAL ENGINEERING


~ 100 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Output:
The factorial of 7 is 5040

Steps to Print Pattern in Python


➢ Decide the number of rows and columns

▪ There is a typical structure to print any pattern, i.e., the number of rows and
columns. We need to use two loops to print any pattern, i.e., use nested loops.

▪ The outer loop tells us the number of rows, and the inner loop tells us the column
needed to print the pattern.

▪ Accept the number of rows from a user using the input() function to decide the size
of a pattern.

➢ Iterate rows

▪ Next, write an outer loop to Iterate the number of rows using a for loop and range()
function.

➢ Iterate columns

▪ Next, write the inner loop or nested loop to handle the number of columns. The
internal loop iteration depends on the values of the outer loop.

➢ Print star or number

▪ Use the print() function in each iteration of the nested for loop to display the symbol
or number of a pattern (like a star (asterisk *) or number).

➢ Add new line after each iteration of outer loop

▪ Add a new line using the print() function after each iteration of the outer loop so that
the pattern display appropriately

Nested for loop


Ex1:
*
* *
* * *
* * * *
* * * * *

DEPARTMENT OF MECHANICAL ENGINEERING


~ 101 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Program:
rows = int(input('Enter no.of rows : '))
for i in range(rows):
for j in range(i+1):
print('*', end = ' ')
print()

Ex2:
* * * * * *
* * * * *
* * * *
* * *
* *
*
Program:
rows = int(input('Enter no.of rows : '))
for i in range(rows):
#for j in range(rows-i):
for j in range(i, rows):
print('*', end = ' ')
print()
Ex3:
*
* *
* * *
* * * *
* * * * *
* * * * * *
Program:
rows = int(input('Enter no.of rows : '))
for i in range(rows):
for j in range(i,rows):
print(' ', end = ' ')
for j in range(i+1):
print('*', end = ' ')
print()
Ex:
* * * * * *
* * * * *
* * * *
* * *
* *
*
Program:
rows = int(input('Enter no.of rows : '))
for i in range(rows):
for j in range(i+1):
print(' ', end = ' ')
for j in range(i,rows):
print('*', end = ' ')
print()

Ex: Hill pattern:

DEPARTMENT OF MECHANICAL ENGINEERING


~ 102 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL
Enter no.of rows : 6
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * * * * * *
Program:

rows = int(input('Enter no.of rows : '))


for i in range(rows):
for j in range(i,rows):
print(' ', end = ' ')
for j in range(i+1):
print('*', end = ' ')
for j in range(i):
print('*', end = ' ')
print()

Ex: Reverse hill pattern


Enter no.of rows : 6
* * * * * * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
rows = int(input('Enter no.of rows : '))
for i in range(rows):
for j in range(i+1):
print(' ', end = ' ')
for j in range(i,rows):
print('*', end = ' ')
for j in range(i,rows-1):
print('*', end = ' ')
print()

Ex: Diamond pattern


Enter no.of rows : 6
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
rows = int(input('Enter no.of rows : '))
for i in range(rows-1):
for j in range(i,rows):
print(' ', end = ' ')

DEPARTMENT OF MECHANICAL ENGINEERING


~ 103 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

for j in range(i+1):
print('*', end = ' ')
for j in range(i):
print('*', end = ' ')
print()
for i in range(rows):
for j in range(i+1):
print(' ', end = ' ')
for j in range(i,rows):
print('*', end = ' ')
for j in range(i,rows-1):
print('*', end = ' ')
print()

Ex: Double hill pattern


Enter no.of rows : 6
* *
* * * *
* * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * *
Program:
num = int(input('Enter no.of rows : '))
for i in range(1,num+1):
print(' '*(num-i), end = '')
for j in range(1,i+1):
print('*', end =' ')

print(' '*(num-i), end = '')


for k in range(1,i+1):
print('*', end = ' ')
print()

Ex: Enter a number5


**
**
****
****
******
******
********
********
**********
**********
Program:
n=int(input("Enter a number"))
for i in range(1,2*n+1):
if i%2==0:
print("*"*i,end=" ")
else:
print("*"*(i+1),end=" ")
print()

DEPARTMENT OF MECHANICAL ENGINEERING


~ 104 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Ex: Diamond alphabet pattern


A
ABC
ABCDE
ABCDEFG
ABCDEFGHI
ABCDEFG
ABCDE
ABC
A
# diamond alphabet pattern program
n = 5

# Upper triangle shape


for i in range(n):
for j in range(n - i - 1):
print(' ', end='')
for j in range(2 * i + 1):
print(chr(65 + j), end='')
print()

# Lower triangle shape


for i in range(n - 1):
for j in range(i + 1):
print(' ', end='')
for j in range(2*(n - i - 1) - 1):
print(chr(65 + j), end='')
print()

Ex:

Python Program to Check Prime Number


# Program to check if a number is prime or not

num = 29

# To take input from the user


#num = int(input("Enter a number: "))

# define a flag variable


flag = False

# prime numbers are greater than 1


if num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break

DEPARTMENT OF MECHANICAL ENGINEERING


~ 105 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

# check if flag is True


if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")
output:
29 is a prime number
Python Program to Check If Two Strings are Anagram
‘Two strings are said to be anagram if we can form one string by arranging the characters
of another string. For example, Race and Care. Here, we can form Race by arranging the
characters of Care’.

# program
str1 = "Race"
str2 = "Care"
# convert both the strings into lowercase
str1 = str1.lower()
str2 = str2.lower()
# check if length is same
if(len(str1) == len(str2)):
# sort the strings
sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)
# if sorted char arrays are same
if(sorted_str1 == sorted_str2):
print(str1 + " and " + str2 + " are anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
output:
race and care are anagram.

While loop:
'while' loop is used to execute a block of statements repeatedly as long as a condition is
true. Once the condition is false, the loop stops execution and control goes immediate
next statement after while block.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 106 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

▪ The while statement checks the condition. The condition must return a boolean
value. Either True or False.

▪ Next, If the condition evaluates to true, the while statement executes the statements
present inside its block.

▪ The while statement continues checking the condition in each iteration and keeps
executing its block until the condition becomes false.

Why and When to Use while Loop in Python:

• Automate and repeat tasks.: As we know, while loops execute blocks of code over
and over again until the condition is met it allows us to automate and repeat tasks in
an efficient manner.

• Indefinite Iteration: The while loop will run as often as necessary to complete a
particular task. When the user doesn’t know the number of iterations before
execution, while loop is used instead of a for loop

• Reduce complexity: while loop is easy to write. using the loop, we don’t need to
write the statements again and again. Instead, we can write statements we wanted
to execute again and again inside the body of the loop thus, reducing the complexity
of the code

• Infinite loop: If the code inside the while loop doesn’t modify the variables being
tested in the loop condition, the loop will run forever.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 107 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Ex:
To print numbers from 1 to 5 by using while loop
x=1
while x <=5:
print(x)
x=x+1
To display the sum of first n numbers
n=int(input("Enter number:"))
sum=0
i=1
while i<=n:
sum=sum+i
i=i+1
print("The sum of first",n,"numbers is :",sum)

Ex: # Python program to find the sum of integers between 0 and n where
n is provided by user
num = int(input("Enter a number: "))
s = 0
if (num >= 0):
while (num >= 0):
s = s + num
num = num - 1
print('The sum is {}'.format(s))
elif (num < 0):
while (num < 0):
s = s + num
num = num + 1
print('The sum is {}'.format(s))
Sample Input and Output 1:
Enter a number: 250
The sum is 31375

Sample Input and Output 2:


Enter a number: -660
The sum is -218130

Ex:
Python Program to Print the Fibonacci sequence
# Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms

DEPARTMENT OF MECHANICAL ENGINEERING


~ 108 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
output:
How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8

Transfer Statements: Break, Continue, and Pass

Statement Description

Terminate the current loop. Use the break statement to come out of the loop
break
instantly.

continue Skip the current iteration of a loop and move to the next iteration

Do nothing. Ignore the condition in which it occurred and proceed to run the
pass
program as usual

DEPARTMENT OF MECHANICAL ENGINEERING


~ 109 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Break Statement in Python


• The break statement is used inside the loop to exit out of the loop (it may be for or
while). In Python, when a break statement is encountered/written inside a loop, the
loop is immediately terminated/executed, and the program control transfer to the
next statement following the loop, 'else' will not be executed. It reduces execution
time.

• For example, you are searching a specific email inside a file. You started reading a
file line by line using a loop. When you found an email, you can stop the loop using
the break statement.

How break statement works:

numbers = [10, 40, 120, 230]


for i in numbers:
if i > 100:
break
print('current number', i)
We used a break statement along with if statement. Whenever a specific condition
occurs and a break statement is encountered inside a loop, the loop is immediately
terminated, and the program control transfer to the next statement following the loop.

Let’s understand the above example iteration by iteration.

In the first iteration of the loop, 10 gets printed, and the condition i > 100 is checked.
Since the value of variable i is 10, the condition becomes false.

In the second iteration of the loop, 40 gets printed again, and the condition i > 100 is
checked. Since the value of i is 40, the condition becomes false.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 110 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

In the third iteration of the loop, the condition i > 100 becomes true, and the break
statement terminates the loop

Continue Statement

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 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.

How continue statement works:

We used the continue statement along with the if statement. Whenever a specific
condition occurs and the continue statement is encountered inside a loop, the loop
immediately skips the remaining body and moves to the next iteration.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 111 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Example: continue statement in for loop

In this example, we will iterate numbers from a list using a for loop and calculate its
square. If we found a number greater than 10, we will not calculate its square and
directly jump to the next number.

Use the if condition with the continue statement. If the condition evaluates to true,
then the loop will move to the next iteration.

Ex:
numbers = [2, 3, 11, 7]
for i in numbers:
print('Current Number is', i)
# skip below statement if number is greater than 10
if i > 10:
continue
square = i * i
print('Square of a current number is', square)
Output:
Current Number is 2
Square of a current number is 4
Current Number is 3
Square of a current number is 9
Current Number is 11
Current Number is 7
Square of a current number is 49
Pass Statement in Python

➢ In Python, the pass keyword is used to execute nothing; it means, when we don't
want to execute code, the pass can be used to execute empty.

➢ If we want to bypass any code pass statement can be used.

➢ It is beneficial when a statement is required syntactically, but we want we don't


want to execute or execute it later.

➢ The difference between the comments and pass is that, comments are entirely
ignored by the Python interpreter, where the pass statement is not ignored.

➢ Suppose we have a loop, and we do not want to execute right this moment, but we
will execute in the future. Here we can use the pass.

➢ Consider the following example.

Ex:
for i in [12,3,4,5]:

DEPARTMENT OF MECHANICAL ENGINEERING


~ 112 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

if i==4:
pass
print('this is pass block',i)
print(i)
Ex:
# pass is just a placeholder for
# we will adde functionality later.
values = {'P', 'y', 't', 'h','o','n'}
for val in values:
pass

INDEXING IN STRINGS
➢ Indexing: Indexing is used to obtain individual elements from an ordered set data.

➢ Individual elements are accessed directly by specifying the string name followed by a
number in square brackets ([]).

➢ String indexing in Python is zero-based: the first character in the string has index 0,
the next has index 1, and so on. The index of the last character will be the length of
the string minus one.

➢ Python supports both positive indexing and negative indexing.

➢ As we are already discussed, positive indexing moves in forward direction of string


and starts from 0.

➢ Negative indexing moves in reverse direction of string and starts from -1.

-6 -5 -4 -3 -2 -1

R G M C E T

0 1 2 3 4 5

Name = "RGMCET"
>>> Name[0]
'R'
>>> Name[3]
'C'
>>> Name[-1]
'T'
>>> Name[-4]
'M'
>>> Name[6]
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>

DEPARTMENT OF MECHANICAL ENGINEERING


~ 113 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Name[6]
IndexError: string index out of range
>>> Name[-7]
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
Name[-7]
IndexError: string index out of range
>>>

How to find the index value for particular character


varaible name.index(character)
>>> Name.index('M')
2
>>> Name.index('T')
5
>>> len(Name)
6
>>> Name[len(Name)-1]
'T'
>>> Name[-len(Name)]
'R'
>>>
STRING SLICING
• Slicing: Slicing is used to obtain a sequence of elements.

• Slicing is a technique of extracting sub-string or a set of characters that form a


string.
Individual characters in a string can be accessed using square brackets and
indexing.

Syntax: string[start : end : step]

▪ start - index start at which slicing is started

▪ end - index at which slicing is ended, end index is exclusive

▪ step - step value is with which start value gets incremented/decremented.

Note

▪ The default step value in string slicing is 1.

Strings Slicing: syntax: [starting index : ending index+1]

Form of indexing syntax that extracts substrings from a string, known as string slicing.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 114 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

-6 -5 -4 -3 -2 -1

R G M C E T

0 1 2 3 4 5

# Get sub-string using start and end values


>>> Name = "RGMCET"
>>> Name[2:5] # Return a sub-string of characters from 2 to 4, excluding
5
'MCE’
# Get sub-string using only end value
>>> Name[:5] # Assumes start value as 0 & step value as 1 ‘RGMCE'
'RGMCE’
# Get sub-string using only Start value
>>> Name[2:] # Assumes end value as length of the string & step value as
1 ‘MCET'
'MCET’
# Get entire string using slicing
>>> Name[:] # Returns entire string
'RGMCET'
>>> Name[::] # Returns entire string, same as above
'RGMCET'

# Modify/Custom step value


>>> Name[1:5:2]
‘GC’
# Get Sub-string using end and step value
>>> Name[:5:2] # So it assumes default start value as 0
‘RME’
# Get Sub-string using only step value
>>> Name[::2] # So it assumes default start value as 0
‘RME’
>>> Name[-5:-2]
'GMC'
>>> Name[0:6:2]
'RME'
>>> Name[5:0:-2]
'TCG'
>>> Name[::-1] # Reversing a string
'TECMGR'
>>> Name[5:2]
‘ ‘ # null string, We can solve this problem by step value negative
>>> Name[5:2:-1]

DEPARTMENT OF MECHANICAL ENGINEERING


~ 115 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

‘TEC’>>> Name[-6:-1:2]
‘RME’
>>> Name[-2:-6]
‘ ‘ # null string, We can solve this problem by
step value negative
>>> Name[-2:-6:-1]
‘ECMG’
Name [3] ='S'
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
Name [3] ='S'
TypeError: 'str' object does not support item assignment
>>> Name = "RGMCET"
>>> Name = Name.replace('C','S')
>>> Name
'RGMSET'
>>>

STRING METHODS

1. Functions of String Data Type


string = 'welcome To Python'
print(string.capitalize()) # used to capitalize first letter of string
print(string.upper()) #used to change entire string to upper case
print(string.lower()) #used to change entire string to lower case.
print(string.title()) #used to change string to title case i.e. first
characters of all the words of string are capitalized.
print(string.swapcase())#used to change lowercase characters into
uppercase and vice versa
print(string.split()) #used to returns a list of words separated by
space

Welcome to python
WELCOME TO PYTHON
welcome to python
Welcome To Python
WELCOME tO pYTHON
['welcome', 'To', 'Python']

DEPARTMENT OF MECHANICAL ENGINEERING


~ 116 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

a = "hello"
print(a.center(10, '&')) #Here the width is 10 and the string length is
5, so now we need to fill the remaining width(10 - 5 = 5) with '&'
special character.
b = "Python"
print(b.center(10, '*'))

&&hello&&&
**Python**

2.Methods Of Strings
a = "happy married life happy birthday birthday baby"
#returns the number of occurrences of substring in particular string.
If the substring does not exist, it returns zeroo
print(a.count('happy'))
a = "java is simple"
print(a.replace('java' ,'Python'))

2
Python is simple
java is simple

b = '.'
List_1 = ['www', 'rgmcet', 'com']
#returns a string concatenated with the elements of an iterable. (Here
“List_1” is the iterable)
print(b.join(List_1))

www.rgmcet.com

string = 'Python'
print(string.isupper()) # used to check whether all characters
(letters) of a string are uppercase or not.
print(string.islower()) #used to check whether all characters (letters)
of a string are lowercase or not.
print(string.isalpha()) #used to check whether a string consists of
alphabetic characters only or not.
print(string.isalnum()) #used to check whether a string consists of

DEPARTMENT OF MECHANICAL ENGINEERING


~ 117 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

alphanumeric characters(both alphabets and digits, but not special


characters).

False
False
True
True

string_1 ='56789'
string_2 = 'rgm03'
print(string_1.isdigit()) #used to check whether a string consists of
digits only or not. If the string contains only digits then it returns
True, otherwise False.
print(string_2.isdigit())

True
False

string_1 = 'Mechanical Engineering'


string_2 =' '
print(string_1.isspace()) #checks whether a string consists of spaces
only or not. If it contains only white spaces then it returns True
otherwise False
print(string_2.isspace())

False
True

string_1 ='Mechanical Engineering'


string_2 ='Rajeev gandhi memorial College of Engineering and
technology'
print(string_1.istitle()) #checks whether every word of a string starts
with upper case letter or not.
print(string_2.istitle())

True
False

DEPARTMENT OF MECHANICAL ENGINEERING


~ 118 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

3. Escape Sequences in Strings


print("hello\npython") # will print result as follows
print("hello\\how are you") # will print result as follows. It returns
one single backslash.
str = "Hello\tPython\nPython is very interesting"
print(str) # will print result as follows
print(repr(str))# Some times we want the escape sequence to be printed
as it is without being interpreted as special.
print(r"Hello\tPython\nPython is very interesting") # We can also use
both 'r'and 'R'. Internally they called repr() method.
print(R"Hello\tPython\nPython is very interesting") # We can also use
both 'r'and 'R'. Internally they called repr() method.
hello
python
hello\how are you
Hello Python
Python is very interesting
'Hello\tPython\nPython is very interesting'
Hello\tPython\nPython is very interesting
Hello\tPython\nPython is very interesting

4. Methods of strings
#startswith(substring)
string = 'department of mechanical engineering'
print(string.startswith('m')) #checks whether the main string starts
with given sub string. If yes it returns True, otherwise False.
print(string.endswith('g')) # checks whether the string ends with the
substring or not.
print(len(string)) # returns the length of the string or to find the
number of characters present in the string
print(min(string)) # returns the minimum character in the string
print(max(string)) # returns the maximum character in the string
print(string.find('of')) #returns the index of the first occurrence of
the substring, if it is found, otherwise it returns -1

DEPARTMENT OF MECHANICAL ENGINEERING


~ 119 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

print(string.rfind('e')) #The rfind() method finds/returns the index of


the last occurrence of the specified value/substring, if it is found,
otherwise it returns -1.
print(string.index('o')) #The index() method is almost the same as the
find() method, the only difference is that the index method will get
ValueError, if specified substring is not available.
print(string.rindex('ment')) #Python string method rindex() returns the
last index where the substring str is found, or raises an exception if
no such index exists.

False
True
36

t
11
31
11
6

# Removing spaces from the string


string = ' department of mechanical engineering '
print(string.strip()) #used To remove spaces both sides
print(string.lstrip()) #used To remove blank spaces present at the
beginning of the string (i.e.,left hand side)
print(string.rstrip()) #used To remove blank spaces present at end of
the string (i.e.,right hand side)

department of mechanical engineering


department of mechanical engineering
department of mechanical engineering

DEPARTMENT OF MECHANICAL ENGINEERING


~ 120 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

UNIT-III
DATA STRUCTURES

SYLLABUS
Lists: Operations on List, important methods used on list. List comprehensions
Tuples: Operations on tuples, important methods used on tuple
Sets: Operations on sets, important methods used on set
Dictionaries: Operations on Dictionaries, important methods used on dictionaries.

LIST
• List is a collection of items (Python objects)

• The purpose of the list is, to group up the things, which fall under the same category

Examples

• List of grocery items,

• List of employee ids,

• List of book names

• Names of all students

• Roll numbers of all students

• Mobile numbers of all students etc..,

Creating a list in python is putting different comma-separated-values, between square


brackets.

Characteristics

• List maintains the order of data insertion

• Lists are mutable, i.e., we can modify the elements

• Even though the list principle suggests homogeneous data items in it, it is not
mandatory and still allowed to have different types (Heterogeneous data) which
makes it a most powerful tool in Python

DEPARTMENT OF MECHANICAL ENGINEERING


~ 121 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

• List allows duplicates

• Growable in nature, i.e based on our requirement we can increase or decrease the
size.

Applications:

• If the content is keep on changing, better to opt for list type. For example, Youtube
comments or Facebook comments or Udemy reviews (which are keep on changing
day by day).

• Used in JSON (Java Script Object Notation) format to transmit data between web
application and server.

• Used in Databases

• Used in array operations

BASIC LIST OPERATIONS

• Create a list: Create a comma separated list of elements and assign to variable.
• Indexing: Accessing the list items.
• Slicing : accessing the part of the list elements.
• Concatenation: adding the lists
• Updating : Updating the list elements
• Membership: To check the membership of element.
• Comparison
• Repetition

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


list = []
print(list)
print(type(list))

[]
<class 'list'>

DEPARTMENT OF MECHANICAL ENGINEERING


~ 122 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

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


list = [10,20,30,40]
print(list)
print(type(list))

[10, 20, 30, 40]


<class 'list'>

3. With dynamic input:


list=input("Enter List:") # Entire input is considered as string
print(list)
print(type(list))

Enter List:10, 'mech', 30


10, 'mech', 30
<class 'str'>

list = eval(input("Enter List:"))


print(list)
print(type(list))

Enter List:[10, 'mech', 30]


[10, 'mech', 30]
<class 'list'>

4. With list() function:


l=list(range(0,10,2))
print(l)

[0, 2, 4, 6, 8]

5. With split() function:


s="Learning Python is very very easy !!!"
l=s.split()
print(l)
print(type(l))

DEPARTMENT OF MECHANICAL ENGINEERING


~ 123 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

['Learning', 'Python', 'is', 'very', 'very', 'easy', '!!!']


<class 'list'>

Note:

Sometimes we can take list inside another list, such type of lists are called nested
lists. [10, 20, [30, 40]]

Repetition Operator:

The repetition operator enables the list elements to be repeated multiple times.
list_1 = [1, 2, 3, 4]
list_3 =list_1*3
print(list_3)

[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

Concatenation:

It concatenates the list mentioned on either side of the operator.


list_1 = [1, 2, 3, 4]
list_2= [5, 6, 7, 8]
list_3 =list_1+list_2
print(list_3)

[1, 2, 3, 4, 5, 6, 7, 8]

Membership:

It returns true if a particular item exists in a particular list otherwise false.


list_1 = [1, 2, 3, 4]
print(2 in list_1)
print(5 not in list_1)

True
True

DEPARTMENT OF MECHANICAL ENGINEERING


~ 124 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Length:

It is used to get the length of the list


list_1 = [1, 2, 3, 4]
len(list_1)

#Apply Relational Operator

list_1 = [1, 2, 3, 4]
list_2= [5, 6, 7, 8]
print(list_1 == list_2)
print(list_1 != list_2)
print(list_1>list_2)# it is based on the first element
print(list_1<list_2)
list_1 = [1, 2, 3, 4]
list_2= [1, 6, 7, 8]
print(list_1>list_2)
# it is based on the second element, if the first element in list is sa
me
print(list_1<list_2)
print(list_1>=list_2)
print(list_1<=list_2)

False
True
False
True
False
True
False
True

DEPARTMENT OF MECHANICAL ENGINEERING


~ 125 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Updating
list = [1,4,8,9,13]
list[1] = 2
print(list)

[1, 2, 8, 9, 13]

ACCESSING ELEMETS OF LIST

• We can access elements of the list either by using index or by using slice operator (:)

• Indexing: Indexing is used to obtain individual elements. List follows zero based index.
ie index of first element is zero and supports both positive and negative indexing.

• Slicing: Slicing is used to obtain a sequence of elements.

1. By using Indexing
list=[10,20,30,40]
print(list[0]) #10
print(list[-1]) #40
print(list[-4]) #10
print(list[10]) #IndexError: list index out of range

10
40
10

-----------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-33-714b2c12ce65> in <module>()
3 print(list[-1]) #40
4 print(list[-4]) #10
----> 5 print(list[10]) #IndexError: list index out of range

IndexError: list index out of range

list = [10,20,[30,40]]
print(list[2])
print(list[2][1])

[30, 40]
40

DEPARTMENT OF MECHANICAL ENGINEERING


~ 126 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

2. By using slice operator:

syntax: listname[start: stop: step]


l = [10,20,30,40,50,60, 70, 80, 90, 100]
print(l[0:4])
print(l[0: 5: 2])
print(l[:5]) # Taking/Returning n first elements of a list------l[:5] i
s equivalent to l[0:5]. This combination is a handy shortcut to take n
first elements of a list.
print(l[-3:]) #Taking/Returning n last elements of a list
print(l[-3:8]) #We can freely mix negative and positive indexes in star
t and stop positions:
print(l[:-2])#Taking/Returning all but n last elements of a list
print(l[::2]) #Taking/Returning every nth-element of a list
print(l[1::2]) #Here we omit start/stop parameters and use only step. B
y providing start we can skip some elements:
print(l[1:-3:2]) #And if we don’t want to include some elements at the
end, we can also add the stop parameter:
print(l[::-1]) #We can use a negative step to obtain a reversed list:
print(l[-2::-1]) #So, we start from the -2 element (value 90) and go fr
om right to left collecting all the elements in a reversed list.

[10, 20, 30, 40]


[10, 30, 50]
[10, 20, 30, 40, 50]
[80, 90, 100]
[80]
[10, 20, 30, 40, 50, 60, 70, 80]
[10, 30, 50, 70, 90]
[20, 40, 60, 80, 100]
[20, 40, 60]
[100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
[90, 80, 70, 60, 50, 40, 30, 20, 10]

DEPARTMENT OF MECHANICAL ENGINEERING


~ 127 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

List vs mutability:

#Substitute part of a list


l = [10,20,30,40,50,60, 70, 80, 90, 100]
l[:4] = [1,2,3,4]
print(l)

[1, 2, 3, 4, 50, 60, 70, 80, 90, 100]

#Replace Every n-th Element


l = [10,20,30,40,50,60, 70, 80, 90, 100]
l[::2] = [1,2,3,4,5]
print(l)

[1, 20, 2, 40, 3, 60, 4, 80, 5, 100]

Traversing the elements of List:

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


#1. By using while loop:
n=[0,1,2,3,4,5,6,7,8,9,10]
i=0
while i<len(n):
print(n[i])
i=i+1

0
1
2
3
4
5
6
7
8
9
10

DEPARTMENT OF MECHANICAL ENGINEERING


~ 128 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

#By using for loop:


n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
print(n1)

0
1
2
3
4
5
6
7
8
9
10

#To display only even numbers:


n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
if n1%2==0:
print(n1)

0
2
4
6
8
10

#To display elements by index wise:


l=["A","B","C"]
x=len(l)
for i in range(x):
print(l[i],"is available at positive index: ",i,"and at negative inde
x: ",i-x)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 129 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

A is available at positive index: 0 and at negative index: -3


B is available at positive index: 1 and at negative index: -2
C is available at positive index: 2 and at negative index: -1

Important functions of List:

What is the difference between function and method?

In Python you can use both these terms interchangeably.

* Function:

Function by default considered as method also.

If a function is declaring outside a class is called as function.

* Method:

If you are declaring a function inside a class is called as a method.

In other words, if you are calling any function with object reference is called as method.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 130 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Built-in list functions

• all(): Returns True if all the items in the list has a True value.

• any() : Returns True if even one item in the list has a True value.

• enumerate(): Returns an enumerate object consisting of the index and value of all
items of list as a tuple pair.

• len(): This function calculates the length i.e., the number elements in the list.

• list(): This function converts an iterable (tuple, string, set, dictionary) to a list

▪ max(): This function returns the item with the highest value from the list

▪ min():This function returns the item with the lowest value from the list.

▪ sorted(): This function returns a sorted result of the list, with the original list
unchanged.

• sum():This function returns the sum of all elements in the list. This function works only
on numeric values in the list and will error out if the list contains a mix of string and
numeric values.

Built-in list methods

*append(x):

Add a single item to the end of the list

* extend(iterable):

Extend the list with the items of another list or iterable

* insert(index, item):

Insert an item at a position before the element given by index.

* remove(element):

Remove the first item in the list whose value is element

Error if the item doesn't exist with the value element in list

DEPARTMENT OF MECHANICAL ENGINEERING


~ 131 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

* pop(), pop(index):
Removes an item at the given position specified by index
Removes and returns the last element if index is not specified
If an invalid index is specified, then an IndexError is thrown

* count(x):

Return the number of times the item x appears in the list

* sort(key = None, reverse = False):

Sort the items of the list in place in ascending order

If the parameter reverse = True, then the list is sorted in place in descending order

* reverse():

Reverse the order of elements of the list in place

* copy()

Return the shallow copy of the list

Equivalent to a[:]

The above functions and methods are grouped into 3 categories

I. To get information about list:


len(): returns the number of elements present in the list

count(): It returns the number of occurrences of specified item in the list.

index(): function: returns the index of first occurrence of the specified item
n=[10,20,30,40]
print(len(n))

DEPARTMENT OF MECHANICAL ENGINEERING


~ 132 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

n=[1,2,2,2,2,3,3]
print(n.count(1))
print(n.count(2))
print(n.count(3))
print(n.count(4))

1
4
2
0

n=[1,2,2,2,2,3,3]
print(n.index(1)) # 0
print(n.index(2)) # 1
print(n.index(3)) # 5
#print(n.index(4)) #If the specified element not present in the list th
en we will get ValueError.

0
1
5
[(0, 1), (1, 2), (2, 2), (3, 2), (4, 2), (5, 3), (6, 3)]

II. Manipulating Elements of List:

1. append() function:

We can use append() function to add new item ((which can be any Python object, such as
an Integer, String, another List, Dictionary or anything else.) at the end of the existing
python list.

By using this append function, we always add an element at last position.

* Syntax: list.append(item)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 133 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

*append() function only takes a single argument that is the item which is needed to be
added or appended at the end of the list.

* append() Return Value: None

- Obviously, this method would not have anything to return, so it simply returns None.
list=[]
list.append("A")
list.append("B")
list.append("C")
print(list)

['A', 'B', 'C']

#Python List append()

#List of Outdoor Games


outdoor_games = ["Cricket","Football","Basketball","Hockey"]

#List of Indoor Games


indoor_games = ["Chess","Ludo","Snakes & Ladders"]

#appending indoor_games List to outdoor_games List


outdoor_games.append(indoor_games)

#Checking updated List


print(outdoor_games)

['Cricket', 'Football', 'Basketball', 'Hockey', ['Chess', 'Ludo', 'Snak


es & Ladders']]

#Eg: To add all elements to list upto 100 which are divisible by 10
list=[]
for i in range(101):
if i%10==0:
list.append(i)
print(list)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 134 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

#Another way
list= []
for i in range(0,101,10):
list.append(i)
print(list)

[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

2. insert() function:

* The list.insert() method is used to insert an item at a particular index into a given Python
List. The new item to be inserted and the index at which it is to be inserted has to be
provided as the second and first arguments to this method respectively.

list.insert(index, item)
n=[1,2,3,4,5]
n.insert(1,888)
print(n)
print()
[1, 888, 2, 3, 4, 5]
n=[1,2,3,4,5]
n.insert(10,777)
n.insert(-10,999)
print(n)
print(n.index(777))
print(n.index(999))

[999, 1, 2, 3, 4, 5, 777]
6
0

DEPARTMENT OF MECHANICAL ENGINEERING


~ 135 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Note:

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

#Example - Python List insert()


#A List with different collection objects
collections = [(1,2,3),[4,5,6],{7,8,9}]
print("Initial List:",collections)
#Inserting a new List Object at index 0
collections.insert(0,['A','B','C'])
print("Updated List:",collections)
#Inserting a new Set Object at index 2
collections.insert(2,{'D','E','F'})
print("Updated List:",collections)
#Inserting a new Tuple Object at index 4
collections.insert(4,('G','H','I'))
print("Updated List:",collections)

Initial List: [(1, 2, 3), [4, 5, 6], {8, 9, 7}]


Updated List: [['A', 'B', 'C'], (1, 2, 3), [4, 5, 6], {8, 9, 7}]
Updated List: [['A', 'B', 'C'], (1, 2, 3), {'D', 'E', 'F'}, [4, 5, 6],
{8, 9, 7}]
Updated List: [['A', 'B', 'C'], (1, 2, 3), {'D', 'E', 'F'}, [4, 5, 6],
('G', 'H', 'I'), {8, 9, 7}]

DEPARTMENT OF MECHANICAL ENGINEERING


~ 136 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

3. extend() function:

To add all items of one list to another list,we use extend() method.

list1.extend(list2)
order1=["Chicken","Mutton","Fish"]
order2=["RC","KF","FO"]
order1.extend(order2)
print(order1)
print(order2)

['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']


['RC', 'KF', 'FO']

numbers_list = [1,2,3,4,5]
numbers_tuple = (6,7,8,9,10)
numbers_set = {11,12,13,14,15}
print("Original List",numbers_list)
#Extending List using tuple
numbers_list.extend(numbers_tuple)
print("Extended List:",numbers_list)
#Extending List using set
numbers_list.extend(numbers_set)
print("Extended List:",numbers_list)

Original List [1, 2, 3, 4, 5]


Extended List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Extended List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

order1=["Chicken","Mutton","Fish"]
order2=["RC","KF","FO"]
order3 = order1 + order2
print(order1)
print(order2)
print(order3)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 137 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

['Chicken', 'Mutton', 'Fish']


['RC', 'KF', 'FO']
['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']

order=["Chicken","Mutton","Fish"]
order.extend("Mushroom") # It adds every character as a single element
to the list
print(order)

['Chicken', 'Mutton', 'Fish', 'M', 'u', 's', 'h', 'r', 'o', 'o', 'm']

Explanation :

Here, 'Mushroom' is a string type, in this string 8 elements are there. These elements are
added seperately.
numbers_list = [1,2,3,4,5]
numbers_list_2 = ["A","B","C","D","E"]
numbers_tuple = (6,7,8,9,10)
numbers_set = {11,12,13,14,15}
print("Original List",numbers_list)
#Concatenating numbers_list_2 into numbers_list
numbers_list = numbers_list + numbers_list_2
#OR
#numbers_list += numbers_list_2
#Extending List using tuple
numbers_list += numbers_tuple
print("Extended List:",numbers_list)
#Extending List using set
numbers_list += numbers_set
print("Extended List:",numbers_list)

Original List [1, 2, 3, 4, 5]


Extended List: [1, 2, 3, 4, 5, 'A', 'B', 'C', 'D', 'E', 6, 7, 8, 9, 10]
Extended List: [1, 2, 3, 4, 5, 'A', 'B', 'C', 'D', 'E', 6, 7, 8, 9, 10,
11, 12, 13, 14, 15]

DEPARTMENT OF MECHANICAL ENGINEERING


~ 138 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

4. remove() function:

We can use this function to remove specified item from the list.

If the item present multiple times then only first occurrence will be removed

list.remove(itemToBeRemoved)
n=[10,20,10,30]
n.remove(10)
print(n)

[20, 10, 30]

If the specified item not present in list then we will get ValueError

5. pop() function:

It removes and returns the last element of the list.

This is only function which manipulates list and returns some element.

* The pop() method of the Python List Object is used to remove any item from the list by
using its index. This method also returns the item so removed.

removedItem = list.pop(itemIndex)
n=[10,20,30,40]
print(n.pop())
print(n.pop())
print(n)

40
30
[10, 20]

#A Python List
items = ["Pen", "Whiteboard", "Tablet", "Smartphone", "Cleaner"]
#Removing the item at Index 2 i.e. "Tablet"
removedItem = items.pop(2)
#Printing the so returned Removed item

DEPARTMENT OF MECHANICAL ENGINEERING


~ 139 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

print("Removed Item:",removedItem)
#Negative Indexing Removals
#Another Python List
items = ["Laptop","Bottle","Stick","Speaker","Rubber"]
#Removing the 3rd Last item from the List
#i.e. "Stick"
#using Negative Index -3
removedItem = items.pop(-3)
print("Removed Item", removedItem)

Removed Item: Tablet


Removed Item Stick

numbers = [10, 23, 30, 42, 50, 55, 76]

#Passing Index Out of the Range of the List


#Will raise IndexError: pop index out of range
numbers.pop(8)

-----------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-51-ff7624fa208d> in <module>()
3 #Passing Index Out of the Range of the List
4 #Will raise IndexError: pop index out of range
----> 5 numbers.pop(8)

IndexError: pop index out of range

If the list is empty then pop() function raises IndexError

Note:

1. pop() is the only function which manipulates the list and returns some value

2. In general we can use append() and pop() functions to implement stack


datastructure by using list,which follows LIFO(Last In First Out) order.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 140 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

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.

We can use pop() function in following ways:

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

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

III. Ordering elements of List:

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

list.reverse()
n=[10,20,30,40]
n.reverse()
print(n)

[40, 30, 20, 10]

DEPARTMENT OF MECHANICAL ENGINEERING


~ 141 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

2. sort() function:

In list by default insertion order is preserved. If you want to sort the elements of list
according to default natural sorting order then we should go for sort() method.

* For numbers ==> default natural sorting order is Ascending Order

* For Strings ==> default natural sorting order is Alphabetical Order

* It is used to arrange the order of the items in either Ascending or Descending or in a


custom order.

list.sort(key=keyFunction, reverse=True/False)
n=[20,5,15,10,0]
n.sort()
print(n)

[0, 5, 10, 15, 20]

s=["Dog","Banana","Cat","Apple"]
s.sort()
print(s)

['Apple', 'Banana', 'Cat', 'Dog']

Note:

To use sort() function, compulsory list should contain only homogeneous elements,
otherwise we will get TypeError.
n=[20,10,"A","B"]
n.sort()
print(n)

-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-32-76d0c10ed9e7> in <module>()
1 n=[20,10,"A","B"]
----> 2 n.sort()
3 print(n)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 142 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

TypeError: '<' not supported between instances of 'str' and 'int'

n=['20',"B",'10',"A"]
n.sort()
print(n)

['10', '20', 'A', 'B']

How to sort the elements of list in reverse of default natural sorting order:

One Simple Way


n=[40,10,30,20]
n.sort()
print(n)
n.reverse()
print(n)

[10, 20, 30, 40]


[40, 30, 20, 10]

Alternate Way :

We can sort according to reverse of default natural sorting order by using reverse = True
argument.
n=[40,10,30,20]
n.sort()
print(n) #[10,20,30,40]
n.sort(reverse=True) # Reverse Sort a list i.e. sorting the list in the
Descending order, we just have to specify the argument reverse of the m
ethod sort() as True
print(n) #[40,30,20,10]
n.sort(reverse=False)
print(n) #[10,20,30,40

s=["Dog","Banana","Cat","Apple"]
s.sort(reverse= True) # reverse of Alphabetical order
print(s)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 143 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

['Dog', 'Cat', 'Banana', 'Apple']

In the below example, we have a list of some strings and each of these strings has a
different length. So, here we’re sorting the list according to the length of the strings in
ascending as well as in the descending order.
demo = ["aaaaa","aa","a","aaaaaa","aaaa","aaaaaaa","aaa"]
print("Initial Ordeer: " + str(demo))
demo.sort(key = len)
print("Small To Large: " + str(demo))
demo.sort(key = len, reverse = True)
print("Large To Small: " + str(demo))

Initial Ordeer: ['aaaaa', 'aa', 'a', 'aaaaaa', 'aaaa', 'aaaaaaa', 'aaa']


Small To Large: ['a', 'aa', 'aaa', 'aaaa', 'aaaaa', 'aaaaaa', 'aaaaaaa']
Large To Small: ['aaaaaaa', 'aaaaaa', 'aaaaa', 'aaaa', 'aaa', 'aa', 'a']

Sorting is a Python List using Custom Logic

Here also we’ll make use fo the key argument but to this argument, we’ll provide our own
defined custom function containing the logic of sorting.

I’ve taken a Python List that contains tuples as the items. Each tuple contains 3 numbers.
The list is now sorted according to the ascending order of the sum of the numbers in each
tuple item.
alist = [(12, 0, 9),(11, 1, 2), (12, 5, 3), (5, 3, 0), (3, 4, 8)]
print("Original Order: " + str(alist))
def tupleSum(element):
return sum(element)
alist.sort(key = tupleSum)
print("Ascending Order: " + str(alist))
alist.sort(key = tupleSum, reverse = True)
print("Descending Order: " + str(alist))

Original Order: [(12, 0, 9), (11, 1, 2), (12, 5, 3), (5, 3, 0), (3, 4, 8)]
Ascending Order: [(5, 3, 0), (11, 1, 2), (3, 4, 8), (12, 5, 3), (12, 0, 9)]
Descending Order: [(12, 0, 9), (12, 5, 3), (3, 4, 8), (11, 1, 2), (5, 3, 0)]

DEPARTMENT OF MECHANICAL ENGINEERING


~ 144 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Note:

To use sort() function, compulsory list should contain only homogeneous elements,
otherwise we will get TypeError.
n=[20,10,"A","B"]
n.sort()
print(n)

-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-55-76d0c10ed9e7> in <module>()
1 n=[20,10,"A","B"]
----> 2 n.sort()
3 print(n)

TypeError: '<' not supported between instances of 'str' and 'int'

Python List clear()

The method clear() is used to remove all the items from a given Python List. This method
does not delete the list but it makes the list empty.

Syntax

The following syntax empty the list.

list.clear()
#A list containing some items
items = ["Copy","Pen",10, 1.5, True, ('A','B')]
print("Initial List:",items)
#Clearing all the list items
items.clear()
print("Empty List:",items)

Initial List: ['Copy', 'Pen', 10, 1.5, True, ('A', 'B')]


Empty List: []

DEPARTMENT OF MECHANICAL ENGINEERING


~ 145 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Example. Deleting all list items using del keyword & Slicing Operator

* The code for the following example is exactly the same as above. The difference is just
that we’ve used the del keyword and the slicing operator to delete all the items from the
list instead of the list.clear() method.
#A list containing some items
items = ["Copy","Pen",10, 1.5, True, ('A','B')]
print("Initial List:",items)
#Clearing all the list items
#Using del keyword
del items[:]
print("Empty List:",items)

Initial List: ['Copy', 'Pen', 10, 1.5, True, ('A', 'B')]


Empty List: []

Built-in functions
print(all([' ', ',', '1', '2'])) # only 0 and false are treated as not
true

True

print(all(['', 0, 1]))

False

print(any([' ', ',', '1', '2']))# returns true if there is at least one True (any
thing other than 0 or False) in the list

True

print(list(enumerate(['a','b','c','d','e']))) # if not work use del list

[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]

print(max([1, 2, 3, 4, 5]))

print(min([1, 2, 3, 4, 5]))

DEPARTMENT OF MECHANICAL ENGINEERING


~ 146 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

origlist = [1, 5, 3, 4, 7, 9, 1, 27]


sortedlist = sorted(origlist)
print(sortedlist)

[1, 1, 3, 4, 5, 7, 9, 27]

print(sum([1, 5, 3, 4, 7, 9, 1, 27]))
print(sum([1, 3, 5, 'a', 'b', 4, 6, 7]))

57

-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-74-cb4452331f6b> in <module>()
1 print(sum([1, 5, 3, 4, 7, 9, 1, 27]))
----> 2 print(sum([1, 3, 5, 'a', 'b', 4, 6, 7]))

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Aliasing and Cloning of List objects:

* The process of giving another reference variable to the existing list is called aliasing.

Observe the following Python Code.

* list1 = [1,2,3,4,5]

* list2 = list1

* list1 = [1,2,3,4,5]

* list2 = list1

In the above code, we have a list of 5 items. In the second line, we’ve used the = operator,
thinking it will create a copy of the list into the list2 variable. But is it like that?

DEPARTMENT OF MECHANICAL ENGINEERING


~ 147 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

list2 will not contain a copy of the list1, rather the list2 will only be a new reference variable
for the list1. It means the list of 5 items is now having two names, list1 and list2. In other
words, it does not duplicate the list. Any changes made to list1 will also be reflected in
list2 because the list1 and list2 both point to the same memory address.

To overcome this problem we should go for cloning.

* Cloning :The process of creating exactly duplicate independent object is called cloning.

We can implement cloning by using the following ways:

# 1. slice operator # 2. copy() function

#Python List copy()

The list.copy() method is used to create a copy of the list into a new variable.

Now many of you might be questioning, why we need a method to copy a list into a new
variable when we can simply do it with the assignment operator = (equals to)?

Hence, we need the list.copy() method to actually create a new copy of a given list.

list_copy = list.copy()
#List1
list1 = ["Gurmeet","Jaskaran","Akshit","Sahil"]

#Copying list1 into list2


list2 = list1.copy()

#Making some changes in only list2


list2.append("Sheila")

print("Original List:",list1)
print("Copied List with Changes",list2)

Original List: ['Gurmeet', 'Jaskaran', 'Akshit', 'Sahil']


Copied List with Changes ['Gurmeet', 'Jaskaran', 'Akshit', 'Sahil', 'Sheila']

DEPARTMENT OF MECHANICAL ENGINEERING


~ 148 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Example: Copying a Python List using Slicing Operator

The Slicing operator can also be used to create a fresh new copy of a Python List and this
is illustrated in the following example.
#List1
list1 = ["Gurmeet","Jaskaran","Akshit","Sahil"]
#Copying list1 into list2
#Using Slicing Operator
list2 = list1[:]
#Making some changes in only list2
list2.append("Sheila")
print("Original List:",list1)
print("Copied List with Changes",list2)

Original List: ['Gurmeet', 'Jaskaran', 'Akshit', 'Sahil']


Copied List with Changes ['Gurmeet', 'Jaskaran', 'Akshit', 'Sahil', 'Sheila']

Q. What is the difference between = operator and copy() function?


= operator meant for aliasing copy() function meant for cloning
List comprehensions
* It is a great way of creating lists in Python without the need for individually specifying
every element of the list. This helps you to create logical and very large lists in just a single
line of code, concisely.
* List Comprehension is basically a syntax in Python that lets you define the logic to create
lists dynamically. You basically define how each of the elements has to be created. So,
when you define to the computer how to generate the elements of the list, you eliminate
the need of defining each and every element of the list yourself. The computer will do the
work for you.
* 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]

DEPARTMENT OF MECHANICAL ENGINEERING


~ 149 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

* A list comprehension generally consist of these parts :


Output expression
Input sequence
A variable representing a member of the input sequence and
An optional predicate part.
* Example: a = [x ** 2 for x in range (1, 11) if x % 2 == 1]
* Here:
x ** 2 is output expression,
range (1, 11) is input sequence,
x is variable and
if x % 2 == 1 is predicate part.
Output: [1, 9, 25, 49, 81]
* Consider an example, If you want to store squares of numbers form 1 to 10 in a list,
list_1=[]
for x in range(1,11):
list_1.append(x*x)
print(list_1)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In the above case, the program consisting 4 lines of code. Now for the same purpose we
will write the following code in more concised way.
list_1 = [x*x for x in range(1,21)]
list_2 = [x for x in l1 if x % 2 == 0]
list_3 = [x for x in l1 if x % 2 == 1]
print(list_1)
print(list_2)
print(list_3)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256,
289, 324, 361, 400]
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]
[1, 9, 25, 49, 81, 121, 169, 225, 289, 361]

DEPARTMENT OF MECHANICAL ENGINEERING


~ 150 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

INTRODUCTION TO TUPLES:

• Tuples are like lists, but their elements are fixed; that is, once a tuple is created, you
cannot add new elements, delete elements, replace elements, or reorder the
elements in the tuple.

• The major differences between the two are: Lists are enclosed in square brackets [ ]
and their elements and size can be changed (mutable), while tuples are enclosed in
parentheses () and their elements cannot be changed (immutable).

• Tuples can be thought of as read-only lists.

• Note: Since a tuple is immutable, iterating through a tuple is faster than with a list.
This gives a slight performance improvement. Once a tuple is defined, we cannot
add elements in it or remove elements from it.

• A tuple can be converted into a list so that elements can be modified and converted
back to a tuple.

• 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).

• A tuple is represented using parenthesis ( ). Sometimes parenthesis is optional.

Characteristics
• Maintains the order of the data insertion
• Tuples are immutable
• Tuples can contain the heterogeneous data
• Tuples allows duplicate data

Applications:
• If the content is fixed, better to opt for tuple type.

• For example, In Banks, account type - Only 2 values are there, 1. Savings 2.
Current At runtime account types never going to change throughout Bank Project.
So, to represent bank account types, better to go for the tuple concept. Some other
Examples, Where allowed inputs are fixed (Best suitable type is tuple):

a. Vendor machines (Only accept 2/-,5/- coins only)

b. In the Metro stations also, If you want to get the tickets, you have to insert
either 10/- note or 20/- note only

DEPARTMENT OF MECHANICAL ENGINEERING


~ 151 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Understanding basic tuple operations


• Creating a tuple
• indexing
• slicing
• Concatenation
• Repetition
• Membership
• Comparison
1. Creating a tuple

tuple_1 =5,6, 8, 9
tuple_2 =(5, 6, 8, 9)
print(tuple_1)
print(tuple_2)
print(type(tuple_1))
print(type(tuple_2))

(5, 6, 8, 9)
(5, 6, 8, 9)
<class 'tuple'>
<class 'tuple'>

# empty tuple
tuple =()
print(tuple)
print(type(tuple))

()
<class 'tuple'>

Note:

We have to take special care about single valued tuple. compulsory the value should
ends with comma, otherwise it is not treated as tuple.

tuple = (10)
print(tuple)
print(type(tuple))

DEPARTMENT OF MECHANICAL ENGINEERING


~ 152 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

10
<class 'int'>

tuple = (10,)
print(tuple)
print(type(tuple))

(10,)
<class 'tuple'>

tuple = (10,20,30,)
print(tuple)
print(type(tuple))

(10, 20, 30)


<class 'tuple'>

By using tuple() function:

if you have any sequence (i.e., string, list, range etc.,) which can be easily converted into
a tuple by using tuple() function.

list=[10,20,30]
t=tuple(list)
print(t)
print(type(t))

(10, 20, 30)


<class 'tuple'>

t=tuple(range(10,20,2))
print(t)
print(type(t))

(10, 12, 14, 16, 18)


<class 'tuple'>

t = tuple('engineering')
print(t)
print(type(t))

('e', 'n', 'g', 'i', 'n', 'e', 'e', 'r', 'i', 'n', 'g')
<class 'tuple'>

DEPARTMENT OF MECHANICAL ENGINEERING


~ 153 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Accessing elements of tuple:

We can access elements of a tuple either by using index or by using


slice operator.

#1. By using index:


t=(10,20,30,40,50,60)
print(t[0]) #10
print(t[-1]) #60
print(t[100]) #IndexError: tuple index out of range

10
60

-----------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-13-ba1aec3992ff> in <module>()
3 print(t[0]) #10
4 print(t[-1]) #60
----> 5 print(t[100]) #IndexError: tuple index out of range

IndexError: tuple index out of range

#2. By using slice operator:


t=(10,20,30,40,50,60)
print(t[2:5]) #30,40,50
print(t[2:100]) # 30,40,50,60
print(t[::2]) #10,30,50

(30, 40, 50)


(30, 40, 50, 60)
(10, 30, 50)

t= tuple('engineering')
print(t[0])
print(t[1:5:1])
print(t[-2:-5:-1])

DEPARTMENT OF MECHANICAL ENGINEERING


~ 154 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

e
('n', 'g', 'i', 'n')
('n', 'i', 'r')

Tuple vs immutability:

Once we creates tuple,we cannot change its content. Hence tuple objects
are immutable.

t=(10,20,30,40)
t[1]=70
print(t)

-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-16-e0f1d773bd10> in <module>()
1 t=(10,20,30,40)
----> 2 t[1]=70
3 print(t)

TypeError: 'tuple' object does not support item assignment

# Modifying Tuple Items


aTuple = ("Tutorial","Lesson","Teaching", 21)
#Converting Tuple To List
aList = list(aTuple)
#Modify Items
aList[1] = "Hello"
aList[2] = "Good"
#Converting List Back to Tuple
aTuple = tuple(aList)
#Modified tuple
print(aTuple)

('Tutorial', 'Hello', 'Good', 21)

Mathematical operators for tuple:

We can apply + and * operators for tuple

DEPARTMENT OF MECHANICAL ENGINEERING


~ 155 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

#1. Concatenation Operator(+):


t1=(10,'mech',30, 'engineering')
t2=(40,'how',60, 'well')
t3=t1+t2
print(t3)

(10, 'mech', 30, 'engineering', 40, 'how', 60, 'well')

t1 = 10,20,30,40
t2 = 10,20,30,40
t3 = t1 + t2 # because list and tuple allow duplicates, so you will get
all the elements
print(t3)

(10, 20, 30, 40, 10, 20, 30, 40)

#2. Multiplication operator (or) repetition operator(*):


t1=(10,20,30)
t2=t1*3
print(t2) #(10,20,30,10,20,30,10,20,30)

(10, 20, 30, 10, 20, 30, 10, 20, 30)

#Iterating a Tuple
aTuple = ("Tutorial","Lesson","Teaching", 21)
for item in aTuple:
print(item)

Tutorial
Lesson
Teaching
21

Checking If Items Exists in the Tuple

Membership operators

• in and not in can be used to check if a particular item exists in the tuple or not.

a = (2, 3, 4, 5, 6, 7, 8, 9, 10)
print(5 in a)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 156 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

print(100 in a)
print(2 not in a)

True
False
False

Comparison operators
Returns True if all elements in both tuples are same otherwise returns false.

a = (2, 3, 4, 5, 6, 7, 8, 9, 10)
b = (2, 3, 4)
print(a == b)
print(a != b)
print(a < b)
print(a > b)
print(a <= b)
print(a >= b)

False
True
False
True
False
True

Understanding the Built-in Tuple Functions


List of functions that can be applied on tuple are given below:

#all(): Returns True if all the items in the tuple has a True value
print(all((' ', ',', '1', '2')))

True

#any(): Returns True if even one item in the tuple has a True value
print(any((' ', ',', '1', '2')))

True

DEPARTMENT OF MECHANICAL ENGINEERING


~ 157 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

# enumerate(): Returns an enumerate object consisting of the index and


value of all items of a tuple as pairs
x = (1, 2, 3, 4, 5, 6)
print(tuple(enumerate(x)))

((0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6))

# len(): This function calculates the length i.e., the number elements
in the tuple
x = (1, 2, 3, 4, 5, 6)
print(len(x))

# max(): This function returns the item with the highest value in the
tuple
print(max((1, 2, 3, 4, 5, 6)))
t = ('engineering') # based on unicode values these functions will
work.
print(max(t))

6
r

# min(): This function returns the item with the lowest value in the
tuple
print(min((1, 2, 3, 4, 5, 6)))
t = ('engineering') # based on unicode values these functions will
work.
print(min(t))

1
e

# sorted(): This function returns a sorted result of the tuple which is


a list, with the original tuple unchanged.
origtup = (1, 5, 3, 4, 7, 9, 1, 27)
sorttup = sorted(origtup)
print(sorttup)
print(origtup)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 158 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

[1, 1, 3, 4, 5, 7, 9, 27]
(1, 5, 3, 4, 7, 9, 1, 27)

# sum(): This function returns the sum of all elements in the tuple.
# This function works only on numeric values in the tuple and will
error out if the tuple contains a mix of string and numeric values.
print(sum((1, 5, 3, 4, 7, 9, 1, 27)))
print(sum((1, 'hi', 3, 4, 7, 'how', 1, 27)))

57

-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-34-b7b5c79dffbd> in <module>()
2 # This function works only on numeric values in the tuple and
will error out if the tuple contains a mix of string and numeric
values.
3 print(sum((1, 5, 3, 4, 7, 9, 1, 27)))
----> 4 print(sum((1, 'hi', 3, 4, 7, 'how', 1, 27)))

TypeError: unsupported operand type(s) for +: 'int' and 'str'

# tuple(): This function converts an iterable (list, string, set,


dictionary) to a tuple
x = list("abcdef")
print(x)
print(tuple(x))

['a', 'b', 'c', 'd', 'e', 'f']


('a', 'b', 'c', 'd', 'e', 'f')

Important functions of Tuple


# 1. len():It is used to return number of elements present in the
tuple.
t=(10,20,30,40)
print(len(t))

DEPARTMENT OF MECHANICAL ENGINEERING


~ 159 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

# 2. count(): To return number of occurrences of given element in the


tuple
t=(10,20,10,10,20)
print(t.count(10))

# 3. index(): It returns index of first occurrence of the given


element. If the specified element is not available then we will get
ValueError.
t=(10,20,10,10,20)
print(t.index(10)) # 0
print(t.index(30))

-----------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-38-23421a9fb8f3> in <module>()
2 t=(10,20,10,10,20)
3 print(t.index(10)) # 0
----> 4 print(t.index(30))

ValueError: tuple.index(x): x not in tuple

# 4. sorted(): It is used to sort elements based on default natural


sorting order (Ascending order).
t =(10,30,40,20)
print(sorted(t))

[10, 20, 30, 40]

# We can sort according to reverse of default natural sorting order is


as follows:
t =(10,30,40,20)
t1=sorted(t,reverse=True)
print(t1)

[40, 30, 20, 10]

DEPARTMENT OF MECHANICAL ENGINEERING


~ 160 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Tuple Packing and Unpacking:


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

a=10
b=20
c=30
d=40
t=a,b,c,d
print(t) #(10, 20, 30, 40)

(10, 20, 30, 40)

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

a = 10
b = 20
c = 30
d = 40
t =[a,b,c,d]
print(type(t))
print(t)

<class 'list'>
[10, 20, 30, 40]

a = 10
b = 20
c = 30
d = 40
t ={a,b,c,d} # for 'set' order is not important
print(type(t))
print(t)

<class 'set'>
{40, 10, 20, 30}

a = 10
b = 20
c = 30

DEPARTMENT OF MECHANICAL ENGINEERING


~ 161 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

d = 40
t ='a,b,c,d'
print(type(t))
print(t)

<class 'str'>
a,b,c,d

Tuple unpacking :

• Tuple unpacking is the reverse process of tuple packing.

• We can unpack a tuple and assign its values to different variables.

t=(10,20,30,40)
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)

a= 10 b= 20 c= 30 d= 40

Note : This concept is also applicable for any sequence (i.e.,


string,list,set etc.,) concept also.

t=[10,20,30,40]
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)

a= 10 b= 20 c= 30 d= 40

t={10,20,30,40}
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)

a= 40 b= 10 c= 20 d= 30

t='abcd'
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)

a= a b= b c= c d= d

Note:

At the time of tuple unpacking the number of variables and number of values should be
same, otherwise we will get ValueError

DEPARTMENT OF MECHANICAL ENGINEERING


~ 162 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

t=(10,20,30,40)
a,b,c=t
print("a=",a,"b=",b,"c=",c)

-----------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-52-42c848936d4d> in <module>()
1 t=(10,20,30,40)
----> 2 a,b,c=t
3 print("a=",a,"b=",b,"c=",c)

ValueError: too many values to unpack (expected 3)

Tuple Comprehension

• Tuple Comprehension is not supported by Python.

• t= ( x**2 for x in range(1,6))

• Here we are not getting tuple object and we are getting generator
object.

t= ( x**2 for x in range(1,6))


print(type(t))
for x in t:
print(x)

<class 'generator'>
1
4
9
16
25

DEPARTMENT OF MECHANICAL ENGINEERING


~ 163 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Introduction to Set
• A set is a mutable data type and We can add or remove items / elements from it.

• The elements in a Set cannot be changed (immutable).

• The set data type is, as the name implies, a mathematical set. we can perform
operations like union, intersection, difference and symmetric difference.

• Set does not allow duplicates. Set does not maintain order. This is because the
placement of each value in the set is decided by an arbitrary index produced by the
hash() function.

As the implementation of the built-in hash() function is complex to understand now. To


make it simple, assume that, when we pass 'n' to hash() function,i.e, calling hash(n),
returns n%10.
For example, calling hash(35) results 35 % 10, which is 5.
Hashing is the process of translating values to unique numbers, generally called a hash
code. These numbers are utilised by other data structures like sets and dictionaries to
allocate a slot(bucket) in an array.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 164 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

• Internally uses a hash table. Values are translated to indices of the hash table using
the hash() function. When a collision occurs in the hash table, it ignores the element.
▪ This explains, why sets unlike lists and tuples can't have multiple occurrences of the
same element. type() of set is 'set'.
• index and slicing concept is not applicable
• A set is represented with { }.

The main operations that can be performed on a set are:


• Membership test
• Eliminating duplicate entries.
• Mathematical set operations like union, intersection, difference and symmetric
difference.

Characteristics:
• A set is a mutable data type and We can add or remove items / elements from it.
• The elements in a Set cannot be changed (immutable). Insertion order is not
preserved.
• Duplicates are not allowed.
• Indexing and slicing not allowed for the set.
• Heterogeneous elements are allowed.

Creation of Set Objects


i) Creation of set object with single value

s = {10}
print(type(s))
print(s)

<class 'set'>
{10}

ii) Creation of set object with multiple values

numset = {1, 2, 3, 4, 5, 3, 2}
print(numset)

{1, 2, 3, 4, 5}

DEPARTMENT OF MECHANICAL ENGINEERING


~ 165 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

s = {30,40,10,5,20} # in the output order not preserved


print(type(s))
print(s[0])

<class 'set'>

-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-72e199601121> in <module>()
1 s = {30,40,10,5,20} # in the output order not preserved
2 print(type(s))
----> 3 print(s[0])

TypeError: 'set' object is not subscriptable

s = {30,40,10,5,20} # in the output order not preserved


print(type(s))
print(s[0:6])

<class 'set'>

----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-3077da98f87a> in <module>()
1 s = {30,40,10,5,20} # in the output order not preserved
2 print(type(s))
----> 3 print(s[0:6])

TypeError: 'set' object is not subscriptable

iii) Creation of set objects using set() function

Syntax: s=set(any sequence)

list = [10,20,30,40,10,20,10]
s=set(list)
print(s)

{40, 10, 20, 30}

DEPARTMENT OF MECHANICAL ENGINEERING


~ 166 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

s=set(range(10))
print(s)

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

s = set('mechanical')
print(s)

{'n', 'h', 'c', 'a', 'm', 'e', 'l', 'i'}

Note:

• While creating empty set we have to take special care. Compulsory we should use
set() function.

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

s = {}
print(type(s))

<class 'dict'>

s = set() # set function without any arguments


print(s)
print(type(s))

set()
<class 'set'>

Accessing or Changing Set Items


You can not either access or change a particular set element. The reason being sets are
unindexed.

Loop Through Set Elements


Although you can not access individual set items yet you can always use the Python For
Loop to access one item at a time.

#set of fruits
fruits = {'Apple', 'Banana', 'Cherry', 'Dates'}

#loop through fruits

DEPARTMENT OF MECHANICAL ENGINEERING


~ 167 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

for fruit in fruits:


print(fruit)

Apple
Cherry
Dates
Banana

Note. You can observe in the output that the items are looped through in a different order
than they actually defined set order. This again shows the unindexed and unordered
property of the set.

Check If An item Exists in a Set (Membership Test)


As a set is a collection object, so we can apply the membership operators i.e. in and not
in to find out if a particular item is present in a given set or not. These operators return a
boolean value i.e. True if a given item founds in a given set and False a given item does
not found in a given set.

countries = {"India", "USA", "UK", "Canada", "Japan"}

#Checking if Japan present in countries


#returns True
print("Japan" in countries)

#Checking if Italy present in countries


#returns False
print("Italy" in countries)

#Checking if the UK not present in countries


#returns False
print("UK" not in countries)

#Checking if Brazil not present in countries


#returns True
print("Brazil" not in countries)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 168 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

True
False
False
True

Python set() Operations


1. Set Union

The union of two sets is the set of all the elements of both the sets without duplicates. You
can use the union() method or the | syntax to find the union of a Python set.

A = {1, 2, 3, 4, 5, 6}
B = {4, 5, 6, 7, 8, 9}

#Union of A & B using | Operator


A_UNION_B = A | B

print("A ⋃ B:", A_UNION_B)

#Union of A & B using the union() method


A_UNION_B = A.union(B)
B_UNION_A = B.union(A)

print("A ⋃ B:", A_UNION_B)


print("B ⋃ A:", B_UNION_A)

A ⋃ B: {1, 2, 3, 4, 5, 6, 7, 8, 9}
A ⋃ B: {1, 2, 3, 4, 5, 6, 7, 8, 9}
B ⋃ A: {1, 2, 3, 4, 5, 6, 7, 8, 9}

DEPARTMENT OF MECHANICAL ENGINEERING


~ 169 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

2. Set Intersection

The intersection of two sets is the set of all the common elements of both the sets. You
can use the intersection() method of the & operator to find the intersection of a Python set.

A = {1, 2, 3, 4, 5, 6}
B = {4, 5, 6, 7, 8, 9}

#Intersection of A and B using & Operator


A_INTERSECT_B = A & B

print("A ⋂ B:", A_INTERSECT_B)

#Intersection of A and B using the intersection() method


A_INTERSECT_B = A.intersection(B)
B_INTERSECT_A = B.intersection(A)

print("A ⋂ B:", A_INTERSECT_B)


print("B ⋂ A:", B_INTERSECT_A)

3. Set Difference

If there are two sets, A and B, then the difference of the set B from set A i.e. A - B will be
a set containing all the items that are only present in set A and not in set B. Similarly, the
difference of the set A from set B i.e. B - A will be a set containing all the items that are
only present in set B and not in set A.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 170 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

A = {1, 2, 3, 4, 5, 6}
B = {4, 5, 6, 7, 8, 9}

#Differnce of Set B from Set A


#Using – operator
print(A - B)

#Differnce of the Set A from Set B


#Using – operator
print(B - A)

#Differnce of Set B from Set A


#Using the method difference()
print(A.difference(B))

#Differnce of the Set A from Set B


#Using the method difference()
print(B.difference(A))

{1, 2, 3}
{8, 9, 7}
{1, 2, 3}
{8, 9, 7}

DEPARTMENT OF MECHANICAL ENGINEERING


~ 171 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

4. Set Symmetric Difference

The symmetric difference of the Set A and B is the set of all the elements that are not
common between the two sets. In other words, it is the set of all the elements of union
excluding the intersection elements.

To find out the set difference, you can either use the ^ operator or the
symmetric_difference() method on a given set. The code given below illustrates the usage
of this operator and method.

Other Set Operations in Python

These are not so common, but they're useful in seeing how sets relate to others.

the a.issubset(b) method or <= operator returns true if the a is a subset of b

the a.issuperset(b) method or >= operator returns true if the a is a superset of b

the a.isdisjoint(b) method return true if there are no common elements between sets a and
b

Built-in Functions that work with Python Sets

1. all() Function: This method returns a boolean value i.e. either True or False.

• If all the elements of the iterable object will be True or representing True, it will return

True.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 172 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

• If at least one of the elements of the iterable object will be False or will indicate a False
value, it will return False.

• If the iterable object is empty, it also returns True.

#Example 1. Checking all() Method For Different Iterables


#Boolean List with all items as True
list1 = [True, True, True]
#Numerical Elements
#0 Represents False and all other integers represents True
list2 = [1, 2, 3, 5]

#Boolean List with all items as False


list3 = [False, False, False]
#Numerical Elements
list4 = [0, 0, 0, 0]
#Atleast One-Element is False in the List
list5 = [True, False, True]
list6 = [1, 2, 0, 5]

#Some other Random cases


list7 = [1, 1, True, False, 1]
list8 = [9, False, 5, False]
list9 = [10, 20, 30, True]
list10 = [True, True, 100, 80, 0]

#all() Method Outputs


print(all(list1))
print(all(list2))
print(all(list3))
print(all(list4))
print(all(list5))
print(all(list6))
print(all(list7))
print(all(list8))

DEPARTMENT OF MECHANICAL ENGINEERING


~ 173 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

print(all(list9))
print(all(list10))

#All String Characters represents True


#Although 0 as an integer represents False
#But '0' as a String is True
string1 = "Hello, this is a Python Tutorial!"
string2 = "00000"
string3 = "The number starts with 0 and ends with 1."
string4 = "Why the number starts with 0?"

#Checking all() Method's Return Values


#All True
print(all(string1))
print(all(string2))
print(all(string3))
print(all(string4))
#Integer Keys and only the First Key is False
check1 = {0 : "True", 1 : False}

#String Keys, all True


check2 = {"0" : "False", "1": False}
check3 = {"a" : False, "b": True}

#Boolean Keys, second False


check4 = {True: "ok", False: "Not ok"}

print(all(check1))
print(all(check2))
print(all(check3))
print(all(check4))

True
True
False

DEPARTMENT OF MECHANICAL ENGINEERING


~ 174 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

False
False
False
False
False
True
False
True
True
True
True
False
True
True
False

all() Returns True for all empty Iterables

As mentioned earlier as well, for any iterable containing no elements, this method all() will
always return True.

#Empty Dictionary
print(all({}))

#Empty list
print(all([]))

#Empty tuple
print(all(()))

#Empty String
print(all(""))

True
True
True
True

DEPARTMENT OF MECHANICAL ENGINEERING


~ 175 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

2. Python any() Function


The Python’s built-in function any() is used to check if an iterable python object contains
at least one item that is True. It returns True if the iterable to check contains any True
element and if it does not contain any of the element that is True, it returns False.

#Boolean List with all items as True


list1 = [True, True, True]
#Numerical Elements
#0 Represents False and all other integers represents True
list2 = [1, 2, 3, 5]

#Boolean List with all items as False


list3 = [False, False, False]
#Numerical Elements
list4 = [0, 0, 0, 0]

#Atleast One-Element is False in the List


list5 = [True, False, True]
list6 = [1, 2, 0, 5]

#Some other Random cases


list7 = [1, 1, True, False, 1]
list8 = [9, False, 5, False]
list9 = [10, 20, 30, True]
list10 = [True, True, 100, 80, 0]

#any() Method Outputs


print(any(list1))
print(any(list2))
print(any(list3))
print(any(list4))
print(any(list5))
print(any(list6))
print(any(list7))

DEPARTMENT OF MECHANICAL ENGINEERING


~ 176 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

print(any(list8))
print(any(list9))
print(any(list10))

#All String Characters represents True


#Although 0 as an integer represents False
#But '0' as a String is True
string1 = "Hello, this is a Python Tutorial!"
string2 = "00000"
string3 = "The number starts with 0 and ends with 1."
string4 = "Why the number starts with 0?"

#Checking any() Method's Return Values


#All True
print(any(string1))
print(any(string2))
print(any(string3))
print(any(string4))

#Integer Keys and only the First Key is False


check1 = {0 : "True", 1 : False}

#String Keys, all True


check2 = {"0" : "False", "1": False}
check3 = {"a" : False, "b": True}

#Boolean Keys, second False


check4 = {True: "ok", False: "Not ok"}

#Single Key False

check5 = {False: "Not ok!"}

DEPARTMENT OF MECHANICAL ENGINEERING


~ 177 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

True
True
False
False
True
True
True
True
True
True
True
True
True
True

Applying any() on Empty Iterables

For any of the empty iterables whether it’s a Python List, Dictionary, Tuple or a String, this
method is going to return False always.

#Empty Dictionary
print(any({}))

#Empty list
print(any([]))

#Empty tuple
print(any(()))

#Empty String
print(any(""))

False
False
False
False

DEPARTMENT OF MECHANICAL ENGINEERING


~ 178 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Python enumerate() Function


In python, enumerate() is a very useful function that can automatically assign sequenced
numbering to different iterable objects. This function will return an Enumerate Type object,
which can be easily iterated using Python For Loop or While Loop. You can also directly
convert this enumerate type object into a more readable iterable like Python List.

Syntax

The syntax of the enumerate() function is given below.

enumerateObject = enumerate(iterable, start = 0)

vegetables = ["Potato","Tomato","Peas","Cauliflower"]
fruits = ("Mango","Apple","Papaya")
#Non-Numbered List
print(vegetables)
#Non-Numbered tuple
print(fruits)
#Enumerating List
vegetables = enumerate(vegetables)
#Enumerating Tuple, setting starting index as 5
fruits = enumerate(fruits,5)
#Converting Enumerable Object To Tuple
vegetables = tuple(vegetables)
#Converting Enumerable Object To List
fruits = list(fruits)
#Numbered vegetables Tuple
print(vegetables)
#Numbered fruits List
print(fruits)

['Potato', 'Tomato', 'Peas', 'Cauliflower']


('Mango', 'Apple', 'Papaya')

-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-26-0b17de878f2a> in <module>()
12 vegetables = tuple(vegetables)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 179 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

13 #Converting Enumerable Object To List


---> 14 fruits = list(fruits)
15 #Numbered vegetables Tuple
16 print(vegetables)
TypeError: 'list' object is not callable

Doing iteration using enumerate()

You can also do numbered iteration using the enumerate() function easily.
The following example illustrates the same.

cities = ["Ludhiana","Chandigarh","Amritsar","Jalandhar"]
print("List of Cities")
for city in cities:
print(city)

print("\nList of Cities with Numbering")


for city in enumerate(cities):
print(city)

print("\nList of Cities with Ranks")


for rank, city in enumerate(cities):
print(rank, city)

print("\nList of Cities With Rank Starting From 3")


for rank, city in enumerate(cities, 3):
print(rank, city)

List of Cities
Ludhiana
Chandigarh
Amritsar
Jalandhar

List of Cities with Numbering


(0, 'Ludhiana')
(1, 'Chandigarh')

DEPARTMENT OF MECHANICAL ENGINEERING


~ 180 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

(2, 'Amritsar')
(3, 'Jalandhar')

List of Cities with Ranks


0 Ludhiana
1 Chandigarh
2 Amritsar
3 Jalandhar

List of Cities With Rank Starting From 3


3 Ludhiana
4 Chandigarh
5 Amritsar
6 Jalandhar

Python len() Function


The built-in function len() is used to find out the number of items or elements contained in
a Python Object. For some Pythons, rather than saying finding the number of items, you
can use this function actually to calculate the length of the object.

count = len(sequenceObject)

#An Empty List


aEmptyList = []

#A List with 5 elements


aList = ['A','B','C','D','E']

#A Tuple with 3 elements


aTuple = (1,2,3)

#Range object from 1 To 94


aRange = range(1,95)

#Finding items count using the len() Function


#For each of these collection objects

DEPARTMENT OF MECHANICAL ENGINEERING


~ 181 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

print(len(aEmptyList))
print(len(aList))
print(len(aTuple))
print(len(aRange))

0
5
3
94

Calculating Length of String and Bytes Objects using len() Method

#An Empty String


anEmptyString = ""

#An Empty Byte object


anEmptyBytesObject = b''

#String with some chracters


aString = "Python @ WTMatter.com"

#Byte Oject with some chracters


aByteObject = b'Enjoy Python Programming!'

#Byte Object
unicodeByte =
b'\xe0\xa4\xa8\xe0\xa4\xae\xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\x95\xe0\xa4\
xbe\xe0\xa4\xb0'

#Finding Length of each of these objects


print(len(anEmptyString))
print(len(anEmptyBytesObject))
print(len(aString))

DEPARTMENT OF MECHANICAL ENGINEERING


~ 182 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

print(len(aByteObject))
print(len(unicodeByte))

0
0
21
25
21

Finding Length of Dictionary and Set Objects using len() Function

#An Empty Dictionary


emptyDictionary = {}

#An Empty Set


emptySet = set()

#An Empty Frozenset


emptyFrozenSet = frozenset(emptySet)

#A Dictionary with some elements


aDictionary = {"Name": "Gurmeet Singh", "Score": 100}

#A Set with some elements


aSet = set(aDictionary)

#A Frozen set with some elements


aFrozenSet = frozenset(aSet)

#Finding elements count for each using len()


print(len(emptyDictionary))
print(len(emptySet))
print(len(emptyFrozenSet))
print(len(aDictionary))
print(len(aSet))
print(len(aFrozenSet))

DEPARTMENT OF MECHANICAL ENGINEERING


~ 183 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

0
0
0
2
2
2

max()

It returns the largest item present in a given set.

min()

It returns the smallest item present in a given set.

sorted()

It returns a new list that contains the set elements in sorted order.

sum()

It returns the sum of all of the set items.

Python Set Methods

1. add(x):
Adds item x to the set

s={10,20,30}
s.add(40); # ';' is optional for python statements
print(s)

{40, 10, 20, 30}

s={10,20,30}
s.add('mechanical'); # ';' is optional for python statements
print(s)

{'mechanical', 10, 20, 30}

DEPARTMENT OF MECHANICAL ENGINEERING


~ 184 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

2. update(x, y, z)
It updates the set after doing union of itself with another set.

* This method is used to add multiple items to the set.

* 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

s={10,20,30}
s.update('mechanical'); # ';' is optional for python statements
print(s)

{'n', 10, 'h', 'i', 'c', 'a', 'm', 20, 'e', 'l', 30}

s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5))
print(s)

{0, 1, 2, 3, 4, 40, 10, 50, 20, 60, 30}

s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5),100)
print(s)

-----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-36-96e519440e16> in <module>()
1 s={10,20,30}
2 l=[40,50,60,10]
----> 3 s.update(l,range(5),100)
4 print(s)

TypeError: 'int' object is not iterable

s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5),'100')
print(s)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 185 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

{0, 1, 2, 3, 4, '0', 40, 10, '1', 50, 20, 60, 30}

s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5),'mechanical')
print(s)

{0, 1, 2, 3, 4, 10, 'c', 20, 30, 40, 50, 'm', 60, 'h', 'a', 'i', 'n',
'e', 'l'}

s =set()
s.update(range(1,10,2),range(0,10,2))
print(s)

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

Q. What is the difference between add() and update() functions in set?

We can use add() to add individual item to the Set,whereas 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 like strings, lists, tuple,
dictionary, set etc.

3. copy():
Returns copy of the set. It is cloned object (Backup copy)

s={10,20,30}
s1=s.copy()
print(s1)
print(s)

{10, 20, 30}


{10, 20, 30}

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

s={40,10,30,20}
print(s)
print(s.pop())

DEPARTMENT OF MECHANICAL ENGINEERING


~ 186 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

print(s.pop())
print(s.pop())
print(s)
print(s.pop())
print(s) # empty set
print(s.pop())

{40, 10, 20, 30}


40
10
20
{30}
30
set()

----------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-41-e74fb62025b2> in <module>()
7 print(s.pop())
8 print(s) # empty set
----> 9 print(s.pop())

KeyError: 'pop from an empty set'

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

If the specified element not present in the Set then we will get KeyError.

s={40,10,30,20}
s.remove(30)
print(s) # {40, 10, 20}
s.remove(50) # KeyError: 50

{40, 10, 20}

-----------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-42-77437864d839> in <module>()

DEPARTMENT OF MECHANICAL ENGINEERING


~ 187 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

2 s.remove(30)
3 print(s) # {40, 10, 20}
----> 4 s.remove(50) # KeyError: 50

KeyError: 50

6. discard(x):
It removes the specified element from the set. If the specified element not present in the
set then we won't get any error.

s={10,20,30}
s.discard(10)
print(s) #{20, 30}
s.discard(50)
print(s) #{20, 30}

{20, 30}
{20, 30}

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

s={10,20,30}
print(s)
s.clear()
print(s)
{10, 20, 30}
set()
Set Comprehension
Set comprehension is possible.
Syntax: # s = {expression for x in sequence condition}
s = {x*x for x in range(6)}
print(s)
{0, 1, 4, 9, 16, 25}
s={2**x for x in range(2,10,2)}
print(s)
{16, 256, 64, 4}

DEPARTMENT OF MECHANICAL ENGINEERING


~ 188 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Introduction to dictionary
• We can use List,Tuple and Set to represent a group of individual objects as a single
entity.
• If we want to represent a group of objects as key-value pairs then we should go for
Dictionary.
• Dictionary is an unordered collections of unique values stored in key and value
pairs.
• General usage of dictionaries is to store key-value pairs like :
– Employees and their wages
– Countries and their capitals
– Commodities and their prices
– Students roll numbers and their names
– Mobile numbers and their address
– ipaddress and its domain name
• In a dictionary, the keys should be unique, but the values can change. For example,
the price of a commodity may change over time, but its name will not change.
• Immutable data types like number, string, tuple etc. are used for the key and any
data type is used for the value.
• Dictionaries are represented by curly braces {}.
• The key-value pairs are represented as key : value.
• For example, daily temperatures in major cities are mapped into a dictionary as {
"Hyderabad" : 27 , "Chennai" : 32 , "Mumbai" : 40 }.

Key features of Dictionary Data type :


1. Duplicate keys are not allowed but values can be duplicated.
2. Hetrogeneous objects are allowed for both key and values.
3. insertion order is not preserved.
4. Dictionaries are mutable.
5. Dictionaries are dynamic.
6. indexing and slicing concepts are not applicable.

Overview of Operations
• The typical operations that can be performed on a dictionary are:
– Adding elements i.e., Key:Value pairs.
– Accessing elements using the Key with the Index operator [] or using get()
method.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 189 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

– Updating the value of a particular element given in the Key.


– The elements can also be deleted which results in a deletion of both the
key:value pair or deleting the entire dictionary using del() method.
– Iterating through a dictionary for processing the elements in it.

Creation of Dictionary objects


1. If you want to create an empty dictionary, we use the following approaches:
* {}
* dict()
d = {}
print(type(d))
print(d)
# using dict()
dictionary = dict()
print(type(d))
print(dictionary)
<class 'dict'>
{}
<class 'dict'>
{}

2. dictionary with some initial values.


details = {
"Department" : "Mechanical Engineering",
"Established" : 1995,
"College" : "RGMCET",
"Located at": "Nandyal"
}
print(details)
{'Department': 'Mechanical Engineering', 'Established': 1995,
'College': 'RGMCET', 'Located at': 'Nandyal'}

Adding & Changing Values


details = {}
#adding new items
details['department'] = 'mechanical'
details['college'] = 'rgmcet'
details['established'] = 1995
print(details)
{'department': 'mechanical', 'college': 'rgmcet', 'established': 1995}

DEPARTMENT OF MECHANICAL ENGINEERING


~ 190 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

details = {}
#adding new items
details['department'] = 'mechanical'
details['college'] = 'rgmcet'
details['established'] = 1995
print(details)
#changing values
details['department'] = 'computer science'
print(details)
{'department': 'mechanical', 'college': 'rgmcet', 'established': 1995}
{'department': 'computer science', 'college': 'rgmcet', 'established':
1995}

Accessing data from the dictionary


• We can access data by using keys.
• If the specified key is not available then we will get KeyError.
• We can prevent this by checking whether key is already available or not by using in
operator.
details = {
"Department" : "Mechanical Engineering",
"Established" : 1995,
"College" : "RGMCET",
"Located at": "Nandyal"
}
print(details['College'])
print(details['State'])
if 'State' in details:
print(details['State'])
RGMCET
-----------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-20-80c7d8fdf571> in <module>()
6 }
7 print(details['College'])
----> 8 print(details['State'])
9 if 'State' in details:
10 print(details['State'])

KeyError: 'State'

DEPARTMENT OF MECHANICAL ENGINEERING


~ 191 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Example Program Q. Write a program to enter name and percentage marks in a


dictionary and display information on the screen.
rec={}
n=int(input("Enter number of students: "))
i=1
while i <= n:
name=input("Enter Student Name: ")
marks=input("Enter % of Marks of Student: ")
rec[name]=marks
i=i+1
print("Name of Student","\t","% of Marks")
for x in rec:
print("\t",x,"\t",rec[x])
Enter number of students: 2
Enter Student Name: rai
Enter % of Marks of Student: 67
Enter Student Name: giri
Enter % of Marks of Student: 69
Name of Student % of Marks
rai 67
giri 69

Deleting the elements from Dictionary


Syntax : del d[key]
• It deletes entry associated with the specified key.
• If the key is not available then we will get KeyError.
details = {
"Department" : "Mechanical Engineering",
"Established" : 1995,
"College" : "RGMCET",
"Located at": "Nandyal"
}
print(details)

del details['College']
print(details)
{'Department': 'Mechanical Engineering', 'Established': 1995,
'College': 'RGMCET', 'Located at': 'Nandyal'}
{'Department': 'Mechanical Engineering', 'Established': 1995, 'Located
at': 'Nandyal'}

DEPARTMENT OF MECHANICAL ENGINEERING


~ 192 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Printing Dictionary Values using key


details = {
"Department" : "Mechanical Engineering",
"Established" : 1995,
"College" : "RGMCET",
"Located at": "Nandyal"
}
for key in details:
print(details[key])
Mechanical Engineering
1995
RGMCET
Nandyal

Printing Dictionary Values using value()


details = {
"Department" : "Mechanical Engineering",
"Established" : 1995,
"College" : "RGMCET",
"Located at": "Nandyal"
}
print(details.values())
for value in details.values():
print(value)
dict_values(['Mechanical Engineering', 1995, 'RGMCET', 'Nandyal'])
Mechanical Engineering
1995
RGMCET
Nandyal

Understanding dictionary functions


all(): Returns True if all the keys of the dictionary are true, else false if the dictionary is
empty
dict1 = {1:'alpha', 2:'beta', 3:'gamma', 4:'music'}
print(all(dict1)) *True
dict2 = {1:'alpha', 2:'', '':'gamma', 4:'music'}
print(all(dict2))
False
any(): Returns True if any key of the dictionary is True else False, if the dictionary is
empty.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 193 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

dict2 = {1:'alpha', 2:'', '':'gamma', 4:'music'}


print(any(dict2))
True
len():This function calculates the length i.e., the number of * key:value pair elements in
the dictionary
dict1 = {1:'alpha', 2:'beta', 3:'gamma', 4:'music'}
print(len(dict1))
4
sorted():This function returns a new sorted list of keys in the * dictionary.
dict1 = {2:'alpha', 3:'beta', 1:'gamma', 4:'music', 6:'video'}
sortlist = sorted(dict1)
print(sortlist)
[1, 2, 3, 4, 6]

Understand the Methods in Dictionary


1. clear()
• This method is used to remove all the items from a given Python Dictionary.
• Syntax: dict.clear()
#Dictionary
#Containing marks data
marks = {
"Gurmeet": 100,
"Simran" : 95,
"Manmeet" : 93,
"Chetan" : 85,
"Sheila" : 89
}

print("Dictionary:",marks)

#Removing all items using clear()


marks.clear()

print("Empty Dictionary:", marks)


Dictionary: {'Gurmeet': 100, 'Simran': 95, 'Manmeet': 93, 'Chetan': 85,
'Sheila': 89}
Empty Dictionary: {}

DEPARTMENT OF MECHANICAL ENGINEERING


~ 194 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

2. copy()
• This method is used to create a shallow copy of a given Python
Dictionary.
dict1 = {
"Apple" : "Fruit",
"Banana" : "Fruit",
"Tomato" : "Vegetable",
"Papaya" : "Fruit",
"Potato" : "Vegetable"
}

dict2 = dict1.copy()

print("Orignal Dictionary:", dict1)


print("Copied Dictionary:", dict2)
Orignal Dictionary: {'Apple': 'Fruit', 'Banana': 'Fruit', 'Tomato':
'Vegetable', 'Papaya': 'Fruit', 'Potato': 'Vegetable'}
Copied Dictionary: {'Apple': 'Fruit', 'Banana': 'Fruit', 'Tomato':
'Vegetable', 'Papaya': 'Fruit', 'Potato': 'Vegetable'}
Example 2. Why you should not use = operator to create a dictionary copy?
dict1 = {
"Apple" : "Fruit",
"Banana" : "Fruit",
"Tomato" : "Vegetable",
"Papaya" : "Fruit",
"Potato" : "Vegetable"
}

#Using = operator for referring the dict1 to another variable dict2


dict2 = dict1

print("dict1:", dict1)
print("dict2:", dict2)

#Clearing the dict2 using clear()


dict2.clear()

#dict1 also got cleared


print("dict1:", dict1)
print("dict2:", dict2)
dict1: {'Apple': 'Fruit', 'Banana': 'Fruit', 'Tomato': 'Vegetable',
'Papaya': 'Fruit', 'Potato': 'Vegetable'}

DEPARTMENT OF MECHANICAL ENGINEERING


~ 195 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

dict2: {'Apple': 'Fruit', 'Banana': 'Fruit', 'Tomato': 'Vegetable',


'Papaya': 'Fruit', 'Potato': 'Vegetable'}
dict1: {}
dict2: {}
dict1 = {
"Apple" : "Fruit",
"Banana" : "Fruit",
"Tomato" : "Vegetable",
"Papaya" : "Fruit",
"Potato" : "Vegetable"
}

#Using copy() method for copying the dict1 to another variable dict1
dict2 = dict1.copy()

print("dict1:", dict1)
print("dict2:", dict2)

#Clearing the dict2 using clear()


dict2.clear()

#Only dict1 got cleared


#dict1 remains unchanged
print("dict1:", dict1)
print("dict2:", dict2)
dict1: {'Apple': 'Fruit', 'Banana': 'Fruit', 'Tomato': 'Vegetable',
'Papaya': 'Fruit', 'Potato': 'Vegetable'}
dict2: {'Apple': 'Fruit', 'Banana': 'Fruit', 'Tomato': 'Vegetable',
'Papaya': 'Fruit', 'Potato': 'Vegetable'}
dict1: {'Apple': 'Fruit', 'Banana': 'Fruit', 'Tomato': 'Vegetable',
'Papaya': 'Fruit', 'Potato': 'Vegetable'}
dict2: {}
Now, here you see, when we have used the copy() method to create a new copy of the
dictionary, the variable dict2 now stores a separate copy of the dict1 at a separate
memory address. Hence, any action performed on either of the dictionaries should not
affect the other dictionary.
As we’ve applied the clear() method only on dict2 here, only the dict2 is cleared, the
dict1 remains unchanged.

3.fromkeys(sequence, value)
The dict.fromkeys() method is used to create a new dictionary from a given sequence of
keys and a defined value by the user.
• newDict = dict.fromkeys(keys, value)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 196 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Generating a dictionary only from a given sequence of Keys


#Defined Sequence of Keys
keys = ["name", "gender", "age", "website"]

#Creating a new Dictionary from Keys Sequence


bio = dict.fromkeys(keys)

print(bio)
{'name': None, 'gender': None, 'age': None, 'website': None}
Creating a dictionary from a given sequence of Keys & a fixed Value
#Defined Sequence of Keys
keys = ["name", "gender", "age", "website"]

#value to be assigned to each of dictionary key item


value = "Hello"

#Creating a new Dictionary from Keys Sequence


bio = dict.fromkeys(keys, value)

print(bio)
{'name': 'Hello', 'gender': 'Hello', 'age': 'Hello', 'website':
'Hello'}

4. d.get(key,defaultvalue)
• If the key is available then returns the corresponding value otherwise returns default
value.
bio = {
"name" : "Gurmeet Singh",
"gender" : "MALE",
"age" : 21,
"website" : "wtmatter.com"
}

#Fetching key value (key exists)


print("Name:",bio.get("name"))

#Fetching key value (key do not exist)


print("Address:",bio.get("address"))

#Fetching key value (key exists)


#Value Argument Defined
print("Age:",bio.get("age", "Key not found!"))

DEPARTMENT OF MECHANICAL ENGINEERING


~ 197 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

#Fetching key value (key do not exist)


#Value Argument Defined
print("Phone:",bio.get("phone", "Key not found!"))
Name: Gurmeet Singh
Address: None
Age: 21
Phone: Key not found!

5. items()
The method dict.items() returns a collection object containing the list of tuples such that
each tuple contains the dictionary items key & value pairs. Let’s say a dictionary contains
5 different key-value pairs. Then this method applied to this dictionary will return dict_list
collection object that will contain five tuples. Each of these tuples will contain exactly two
items, the first item will the key and the second will be the value associated with that
particular key.
#A Dictionary containing 4 items (key-value) pairs
bio = {
"name" : "Gurmeet Singh",
"gender" : "MALE",
"age" : 21,
"website" : "wtmatter.com"
}

#Using the items() method


items = bio.items()

print(items)
dict_items([('name', 'Gurmeet Singh'), ('gender', 'MALE'), ('age', 21),
('website', 'wtmatter.com')])
Modifying the dictionary after using the method items()
#A Dictionary containing 4 items (key-value) pairs
bio = {
"name" : "Gurmeet Singh",
"gender" : "MALE",
"age" : 21,
"website" : "wtmatter.com"
}

#Using the items() method


items = bio.items()

print("Before Modification", items)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 198 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

#Modifying the original dictionary after using the items() method

bio["country"] = "India"

print("After Modification", items)


Before Modification dict_items([('name', 'Gurmeet Singh'), ('gender',
'MALE'), ('age', 21), ('website', 'wtmatter.com')])
After Modification dict_items([('name', 'Gurmeet Singh'), ('gender',
'MALE'), ('age', 21), ('website', 'wtmatter.com'), ('country',
'India')])

6. Python Dictionary keys()


• The method dict.keys() is used to return a list of keys present in a given dictionary
as a view object. This view object is dict_keys.
Fetching the list of keys in a Dictionary
#A Dictionary with 4 items
bio = {
"name": "Gurmeet Singh",
"age" : 21,
"gender" : "MALE",
"country" : "India"
}

#Fetching Dictionary keys using keys() method


keysList = bio.keys()

print("List of Keys in bio:", keysList)


List of Keys in bio: dict_keys(['name', 'age', 'gender', 'country'])

7. Python Dictionary setdefault()


• The method dict.setdefault() is used to fetch the value for a key in a given dictionary
and if the key does not exist in the dictionary, this method will insert a default value
for that particular key.
• Syntax: key_value = dict.setdefault(key, default_value)
#Working of setdefault() if the key is present in the Dictionary
#A Dictionary with 4 items
bio = {
"name": "Gurmeet Singh",
"age" : 21,
"gender" : "MALE",
"country" : "India"

DEPARTMENT OF MECHANICAL ENGINEERING


~ 199 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

#key exists
#only key argument passed
value = bio.setdefault("age")

print("Value Returned:", value)


print("Dictionary bio:", bio)

#key exists
#both arguments passed
value = bio.setdefault("age", 25)

print("Value Returned:", value)


print("Dictionary bio:", bio)
Value Returned: 21
Dictionary bio: {'name': 'Gurmeet Singh', 'age': 21, 'gender': 'MALE',
'country': 'India'}
Value Returned: 21
Dictionary bio: {'name': 'Gurmeet Singh', 'age': 21, 'gender': 'MALE',
'country': 'India'}
#Working of setdefault() if the key is not present in the Dictionary
#A Dictionary with 4 items
bio = {
"name": "Gurmeet Singh",
"age" : 21,
"gender" : "MALE",
"country" : "India"
}

#key not exists


#only key argument passed
value = bio.setdefault("website")

print("Value Returned:", value)


print("Dictionary bio:", bio)

#key not exists


#both arguments passed
value = bio.setdefault("height", "180cms")

print("Value Returned:", value)


print("Dictionary bio:", bio)

DEPARTMENT OF MECHANICAL ENGINEERING


~ 200 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Value Returned: None


Dictionary bio: {'name': 'Gurmeet Singh', 'age': 21, 'gender': 'MALE',
'country': 'India', 'website': None}
Value Returned: 180cms
Dictionary bio: {'name': 'Gurmeet Singh', 'age': 21, 'gender': 'MALE',
'country': 'India', 'website': None, 'height': '180cms'}
8. Python Dictionary update()
The method dict.update() is used to add new items to a given dictionary using another
Python Dictionary object or such an iterable object that contains (key, value) pair based
items.
Note. The new items from another dictionary or iterable are added as it is in case their
keys are already not present in the dictionary on which the method is applied. But in case,
the dictionary already contains the same key(s), the key(s) values get updated with the
value(s) from the new dictionary or iterable.
#Adding more items from another dictionary using the method
items = {
"India" : "INR",
"USA" : "USD",
"Canada" : "CAD",
"Italy" : "EUR"
}

moreItems = {
"Japan" : "JPY",
"Brazil" : "BRL"
}

print("Initial Items:", items)

#Adding Items from moreItems into items


items.update(moreItems)

print("Updated Items:", items)


Initial Items: {'India': 'INR', 'USA': 'USD', 'Canada': 'CAD', 'Italy':
'EUR'}
Updated Items: {'India': 'INR', 'USA': 'USD', 'Canada': 'CAD', 'Italy':
'EUR', 'Japan': 'JPY', 'Brazil': 'BRL'}
#Adding items from a (key, value) pair based Iterable
items = {
"India" : "INR",
"USA" : "USD",
"Canada" : "CAD",

DEPARTMENT OF MECHANICAL ENGINEERING


~ 201 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

"Italy" : "EUR"
}

#An Iterable containing (key, value) pair-based items


moreItems = [
("Japan", "JPY"),
("Brazil", "BRL")
]

print("Initial Items:", items)

#Adding Items from moreItems into items


items.update(moreItems)

print("Updated Items:", items)


Initial Items: {'India': 'INR', 'USA': 'USD', 'Canada': 'CAD', 'Italy':
'EUR'}
Updated Items: {'India': 'INR', 'USA': 'USD', 'Canada': 'CAD', 'Italy':
'EUR', 'Japan': 'JPY', 'Brazil': 'BRL'}
#Working of update() without iterables
items = {
"Hello" : 0,
"," : 1,
"How" : 2,
"are" : 3,
}

print("Initial Items:", items)

items.update(you = 4, Gurmeet = 5)

print("Updated Items:", items)


Initial Items: {'Hello': 0, ',': 1, 'How': 2, 'are': 3}
Updated Items: {'Hello': 0, ',': 1, 'How': 2, 'are': 3, 'you': 4,
'Gurmeet': 5}

9. Python Dictionary values()


The method dict.values() is used to get the view object that contains the list of all of the
values of a given dictionary. This method fetches the values from all of the key, value pair
items in the dictionary and show them as a collection object known as the dict_values
object.
#Fetching values form a given Dictionary using the method values()
#A Dictionary of languages

DEPARTMENT OF MECHANICAL ENGINEERING


~ 202 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

languages = {
0 : "English",
1 : "Hindi",
2 : "Punjabi",
3 : "Spanish",
4 : "French"
}

#Getting only Dictionary Values using values()


values = languages.values()

print("Values:", values)
Values: dict_values(['English', 'Hindi', 'Punjabi', 'Spanish',
'French'])
#dict_values gets updated if the dictionary is updated
#A Dictionary of languages
languages = {
0 : "English",
1 : "Hindi",
2 : "Punjabi",
3 : "Spanish",
4 : "French"
}

#Getting only Dictionary Values using values()


values = languages.values()

print("Values Before Adding More Items:", values)

#Adding more Dictionary items


languages[5] = "Tamil"
languages[6] = "Telegu"

print("Values After Adding More Items:", values)


Values Before Adding More Items: dict_values(['English', 'Hindi',
'Punjabi', 'Spanish', 'French'])
Values After Adding More Items: dict_values(['English', 'Hindi',
'Punjabi', 'Spanish', 'French', 'Tamil', 'Telegu'])

10. Python Dictionary pop()


The method dict.pop() is used to remove a particular element from a given dictionary by
its key and this method also returns the removed item value.

DEPARTMENT OF MECHANICAL ENGINEERING


~ 203 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

#Removing the Item from the dictionary using pop(), if the key exists
#A Dictionary of 5 items
items = {
"Brinjal (Eggplant)" : "Vegetable",
"Onion" : "Vegetable",
"Papaya" : "Fruit",
"Mango" : "Fruit",
"Radish" : "Vegetable"
}
print('before pop : ', items)

#Popping the item with key Papaya


value = items.pop("Papaya")

print("items:", items)
print("Returned Value:", value)
before pop : {'Brinjal (Eggplant)': 'Vegetable', 'Onion': 'Vegetable',
'Papaya': 'Fruit', 'Mango': 'Fruit', 'Radish': 'Vegetable'}
items: {'Brinjal (Eggplant)': 'Vegetable', 'Onion': 'Vegetable',
'Mango': 'Fruit', 'Radish': 'Vegetable'}
Returned Value: Fruit
#Working of pop() if the key does not exist
#A Dictionary of 5 items
items = {
"Brinjal (Eggplant)" : "Vegetable",
"Onion" : "Vegetable",
"Papaya" : "Fruit",
"Mango" : "Fruit",
"Radish" : "Vegetable"
}

#Popping the item with key Banana


#Item with this key not present in the dictionary
value = items.pop("Banana")

print("items:", items)
print("Returned Value:", value)
-----------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-51-d120b4ccf672> in <module>()
11 #Popping the item with key Banana
12 #Item with this key not present in the dictionary
---> 13 value = items.pop("Banana")

DEPARTMENT OF MECHANICAL ENGINEERING


~ 204 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

14
15 print("items:", items)

KeyError: 'Banana'
#If the key does not exist in the dictionary but the default argument
is passed
#A Dictionary of 5 items
items = {
"Brinjal (Eggplant)" : "Vegetable",
"Onion" : "Vegetable",
"Papaya" : "Fruit",
"Mango" : "Fruit",
"Radish" : "Vegetable"
}

#Popping the item with key Banana


#Item with this key not present in the dictionary
#Value of default is also passed
value = items.pop("Banana", "Fruit")

print("items:", items)
print("Returned Value:", value)
items: {'Brinjal (Eggplant)': 'Vegetable', 'Onion': 'Vegetable',
'Papaya': 'Fruit', 'Mango': 'Fruit', 'Radish': 'Vegetable'}
Returned Value: Fruit

11. Python Dictionary popitem()


The method dict.popitem() is used to remove the last inserted item from a given Python
Dictionary as of version 3.7 & above. In the earlier versions, this method removes a
random (arbitrary) item from the dictionary.
Note. The last item displaying in a Python Dictionary may not be the actual last inserted
item.
#Working of popitem() method
#A Dictionary with 4 items
bio = {
"name": "Gurmeet Singh",
"age" : 21,
"gender" : "MALE",
"country" : "India"
}

print("Before Last Insertion, bio:", bio)

#last item insertion

DEPARTMENT OF MECHANICAL ENGINEERING


~ 205 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

bio["website"] = "wtmatter.com"

print("After Insertion, bio:", bio)

bio.popitem()

print("After Popping, bio:", bio)


Before Last Insertion, bio: {'name': 'Gurmeet Singh', 'age': 21,
'gender': 'MALE', 'country': 'India'}
After Insertion, bio: {'name': 'Gurmeet Singh', 'age': 21, 'gender':
'MALE', 'country': 'India', 'website': 'wtmatter.com'}
After Popping, bio: {'name': 'Gurmeet Singh', 'age': 21, 'gender':
'MALE', 'country': 'India'}

12.len()
This method returns the length.
dict = {'Name': 'Zara', 'Age': 7};
print ("Length : %d" % len (dict))
Length : 2
Dictionary Comprehensions
• Dictionary comprehension is a method for transforming one dictionary into another
dictionary. During this transformation, items within the original dictionary can be
conditionally included in the new dictionary and each item can be transformed as
needed.
• Dictionary Comprehensions return output in Dictionary format like (key : value) pairs
and Keys should be unique and each key has a respective value.
– {key : value for (key , value) in iterable}
squares={x:x*x for x in range(1,6)}
print(squares)
doubles={x:2*x for x in range(1,6)}
print(doubles)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}

DEPARTMENT OF MECHANICAL ENGINEERING


~ 206 ~
RGM COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS), NANDYAL

Ex: Python Program to Count the Number of Each Vowel

# Program to count the number of each vowels

# string of vowels

vowels = 'aeiou'

ip_str = 'Hello, have you tried our tutorial section yet?'

# make it suitable for caseless comparisions

ip_str = ip_str.casefold()

# make a dictionary with each vowel a key and value 0

count = {}.fromkeys(vowels,0)

# count the vowels

for char in ip_str:

if char in count:

count[char] += 1

print(count)

output:

{'o': 5, 'i': 3, 'a': 2, 'e': 5, 'u': 3}

DEPARTMENT OF MECHANICAL ENGINEERING


~ 207 ~

You might also like