0% found this document useful (0 votes)
46 views25 pages

PP Unit-1 Material

Python

Uploaded by

Dwipendu Kundu
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)
46 views25 pages

PP Unit-1 Material

Python

Uploaded by

Dwipendu Kundu
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/ 25

Python Programming

Unit-1(PART-1)
Introduction to Python:
• High Level language: python is in English. So, we can write and understand very easily.
• Interpreted language: python script is processed at runtime by the interpreter(without any
compilation we can the python script )
• Interactive language: we can easily interact with the interpreter to write and run our python script
• Object Oriented: python is an object oriented, it supports all object oriented concepts like classes,
object, inheritance, exception handling and many other.
• Scripting Language: python is a scripting language

[Scripting language: it is a computer language with the series of commands within a file that
capable of being executed without being compile]

History of Python Language:


• Python is developed by Guido van Rossum in late 80’s and early 90’s at National Research
Institute, Netherlands.
• Python is mainly useful for mathematics and computer science people.
• Python is derived from ABC,Modula-3,C,C++,Algol-68,Smalltalk,Unix shell and other scripting
languages
• It is copyrighted , it means python source code which is now available under GNU General Public
Licence(GPL)
• It is currently maintained by the core development team at a institute which is directed by Guido
Van Rossum
• The first version of python is released in 1991 i.e. Version 1.0
• after python 1,python 2 and python 3 are released
• Current version of python is python 3.8.5
Features of Python:
• Python is Open source
• Python is Easy-to-learn
• Python is Easy-to-read
• Python is Easy-to-maintain
• Python is a broad standard library
• Interactive Mode
• Python is Portable
• Databases
• Python has GUI Programming
Need of Python Programming:
• Python is a general-purpose language, which means it can be used to build just about anything which
will be made easy with the right tools/libraries.
• Professionally, Python is great for
❖ backend web development
❖ data analysis
❖ artificial intelligence
❖ Scientific computing.
• Python is also used to build productivity tools, games, and desktop apps

Applications of Python:
python is very powerful and it is used to develop Software ,Web and Internet based applications,
Desktop based application, Graphic design, Scientific and computational applications, Image processing,
Text processing and Enterprise level applications and many other.

Key applications of python:

• Python is used as embedded scripting language: for Building, Testing, Deployment,


Monitoring the software we can use python.

• Python is used to build 3D software: By using maya tool 3D softwares will build.

• Python is used to develop web base applications using following tools


1. Django & Pyramid

2. Flask & Bottle

3. Plone & Django CMS

Example:
Quora, Google App, Odoo

• Python is used to develop GUI based Desktop applications using following tools
WxPython
Pyqt
Pygtk

• Python is used for Image Processing and python have following tools for doing image
processing
2D: Python has many packages/tools for 2D which are as follows
Inkscape
GIMP
PaintshopPro
Scribus

3D: Python has many packages/tools for 3D which are as follows


Blender
3ds max
Cinema 4D
Houdini
Lightwave
Maya
• Python is used for Scientific and Computational Applications and the tools used for this is
ScientificPython, numericPython

• Python is used to develop games and tools useful to develop games is as follow
PyGame
PySoy
Example:
Civilization-IV, Disney’s toon town online, Vega Strike

• Python is used for Enterprise level applications(business applications)

Examples: Reddit, Youtube,Ola,Uber

• Operating system:

Ubuntu----Ubiquity installer
Fedora----Red Hat
Linux----Anaconda Installer

• Language Development:
Python design and module architecture is used to develop other languages like BOO, Apple swift,
coffee Script, cobra, ocaml

• Python is used for Prototyping

• Python is used for 3D modeling(TOOL NAME: FreeCAD)

• Python is used for mathematics , science and engineering people(TOOL NAME: Scipy)

• Python is used for Data analysis(TOOL NAME:Pandas)

• Python is used for Network programming

• Python is used for Teaching: It is perfect language for teaching programs at the inductory as well
as advanced level

Input-Processing-Output:
• Input: Any information or data sent to a computer for processing is considered input. Input or user
input is sent to a computer using an input devices.
• Processing: Work being done in program
• Output: Any information that is processed by and sent out from a computer or other electronic
device is considered output.
Example:
Question: Write a Program to add two numbers?
Program:
a=int(input(“Enter a ”))
b=int(input(“Enter b”))
c=a+b
print(c)
For above Programs,
Input: let any two integers a,b
Processing: c=a+b
Output: c

Program Development Cycle:

Program Development Cycle is a process that consists of a series of planned activities to develop a
Program.

Following are step involved in Program development cycle:


1. Define and analysis the problem
2. Design
3. Coding & Documentation
4. Testing & Debugging
5. Maintenance
Define and analysis the problem: In this Step we perform following tasks.
• Understanding a Given problem
• Analyze Required Input
• Analyze Desired Output
• What Operation should we perform to achieve problem
• Selection of programming language
Design:
During this phase, we develop a step by step procedure and diagrammatic representation to
solve the problem using the specification given in the previous phase. This phase is very important for
program development.
Coding & Documentation:
This phase uses a programming language to write or implement the actual programming
instructions for the steps defined in the previous phase. In this phase, we construct the actual program.
That means we write the program to solve the given problem using programming languages like C,
C++, Java, Python etc.,
Testing & Debugging:
During this phase, we check whether the code written in the previous step is solving the
specified problem or not. That means we test the program whether it is solving the problem for various
input data values or not. We also test whether it is providing the desired output or not.
Maintenance:
During this phase, the solution (program) is used by the end-user. If the user encounters any
problem or wants any enhancement, then we need to repeat all the phases from the starting, so that the
encountered problem is solved or enhancement is added.

Using REPL Shell:


Shell: shell is nothing but an environment provided for user interaction.

REPL: REPL stands for Read–Eval–Print Loop and is an interactive computer programming
environment that READ single user input, EVALUATE them, and PRINT the result. And the script
written in a REPL environment is executed piecewise.

• To enter into interactive REPL shell type python command in command prompt
vahida@vahida-HP-Notebook:~$ python
Python 2.7.11+ (default, Apr 17 2016, 14:00:29)
Type "help", "copyright", "credits" or "license" for more information.
>>>
• Three greater than symbols (>>>) are used to indicate that we are inside a shell or an interpreter and
it is wait for our instruction.
Example:
vahida@vahida-HP-Notebook:~$ python
Python 2.7.11+ (default, Apr 17 2016, 14:00:29)
Type "help", "copyright", "credits" or "license" for more information.
>>> print ("Hello Python World")
Hello Python World
>>> 2+3
5
>>> x=10
>>> y=20
>>> x+y
30
>>>

• To exit from REPL shell or from interpreter we use exit() command


Example:
vahida@vahida-HP-Notebook:~$ python
Python 2.7.11+ (default, Apr 17 2016, 14:00:29)
Type "help", "copyright", "credits" or "license" for more information.
>>> print ("Hello Python World")
Hello Python World
>>> 2+3
5
>>> x=10
>>> y=20
>>> x+y
30
>>>exit()
vahida@vahida-HP-Notebook:~$

Steps to write and run a python script:


The standard way to save and run a python script is as follow
− Open an editor (notepad filename.py)
− Write the instructions
− Save (Ctrl+save)
− Run the interpreter with the command "python filename.py"

Basics of Python Programming:

Python Identifiers: An identifier is a name given to entities like variables, functions, class, modules and
others objects in the python.

Identifier naming rules:

− Identifier should starts with alphabets (A-Z) or (a-z) and underscore( _ ).


− An identifier cannot starts with digit.
− Keyword cannot be used as identifier.
− We cannot use special symbols like !,@,#,$,% etc in our identifier.
− An identifier can be length.
− Case sensitive
Valid and Invalid Identifier Examples:
AREA →Valid
Area →Valid
2area →Invalid
area2 →Valid
Area-2 →Invalid
Area_2 →Valid
While →Invalid\
Variables:
1. Variables are used to store some information on computer memory.
2. We can store anything using a variable
3. Python is dynamic typed language
4. So, there are no variable declarations in python
5. Everything is an object in python
Python is a Dynamically typed language: No need to specify explicitly what type of thing each data
value is.

c/c++/java: c/c++/java are termed as static typed language because before using any variable we need to
specify explicitly what type of date variable will hold by variable declaration.

Example:
int a=10,b=20,c;
c=a+b;
print(c)
python: python is a dynamic typed language. So, No need to specify explicitly what type of data each
variable holds.

Example:
a=10
b=20
c=a+b
print(c)
Literals:
➢ A literal is a notation for representing a fixed value in source code.
➢ In other words, which type of data we are storing into a variable is treated as literal in python
Python supports following literals
• Int literals:
Example: a=0,b=1,c=2,d=-1,e=-2
• Float literals:
Example: x=3.12,z=6.77893456
• Complex literals: (a+bj)
Example: s=1+12j
• Boolean literals:
Example: status1=True,status2=False
• Special literals:
Example: a=None
• List literal:
Example: a=[10,20,30,40,50,60]
• tuple literal:
Example: a=(10,20,30,40,50,60,10)
• Set literal :
Example: s={10,20,30,40,50,60,10}
• Dictionary literal:
Example: d={key1:value1,key2:value2…}
student_details={1:”ramu”,2:”raju”,3:”suma”}

Assignment: Assignment is associating a name to a value (name=value). The associated name is usually
called a variable.

Assignment syntax in python:


1. <variable>=<value>
Example: x=10
2. <variable>=<expression>
Example: z=x+y

Case 1: if we try to use a name that is not associated with any value, python gives an error message.

Example:
>>> b
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'b' is not defined
>>> b = 4
>>> b
4

Case 2: If you re-assign a different value to an existing variable, the new value overwrites the old value.

Example:
>>> x = 4
>>> x
4
>>> x = 'hello'
>>> x
'hello'

Case 3: It is possible to do multiple assignments at once

Example:
>>> a, b = 1, 2
>>> a
1
>>> b
2
>>> a + b
3

Swapping values of 2 variables in python is very simple


>>> a, b = 1, 2
>>> a, b = b, a
>>> a
2
>>> b

Note:
When executing assignments, python evaluates the right hand side first and then assign these vales to
the variable specified in the left hand side

Keywords:
In Every programming language there are certain words which have a pre-defined meaning, Those words
are called keywords or reserve words. We can’t change its meaning and We can’t be used as an identifier.
Python have following keywords.
And Del from not while
As Elif global or with
Assert Else If pass yield
Break Except import print
Class Exec In raise
continue finally Is return
Def For lambda try

Indentation:
Python forces the user to program in a structured format. Code blocks are determined by the amount
of indentation used. In python, indentation is used to represent start and end of each code block Statements
which go together must have the same indentation. Wrong indentation can give error .For code block use
four spaces for indentation (recommended).
Example without indentation
Script:

print ("hai")
print ("welcome to Python")

C:\Users\HP-PC>python indent.py
File "indent.py", line 2
print("welcome to Python")
^
IndentationError: unexpected indent
Example with indentation
Script:

print("hai")
print("welcome to Python")

C:\Users\HP-PC>python indent.py
Hai
Welcome to Python
Input and Output:

Output in python: print function is used as output function in python.

case1: Printing a simple message


Syntax
print(“message here”)
(or)
print(‘message here’)

Example:
print(“hai welcome to python lab”)
(or)
print(‘hai welcome to python lab’)
Result : hai welcome to python lab

case2: Printing a data inside a variable syntax

Syntax:
print (vn1, vn2, vn3,…….)
Example:
x=10
y=20
print(x,y)
Result:10 20

Case 3:Printing both message and data

Example:
x=10
y=20
print("sum of x and y is",x+y)

Result:
sum of x and y is 30

Input in python: input function are used as input function in python.

Syntax: input function take input as string or a character

variable=input(“message here”)

Example:

x=int(input(“enter x value”))
y=int(input(“enter y value”))
print("sum of x and y is",x+y)
result:

enter x value10
enter y value20
sum of x and y is 30

Comments in Python:
• Comments can be used to explain Python code.
• Comments can be used to make the code more readable.
• Comments will be ignored at the time of program execution.
Single Line Comment:

The line which start with # is treated as single line comment in python.

Multiline Comment:

Multi line comment starts with """(three double quotes) and ends with """(three double quotes).

Example:

"""write a Python Program


to print welcome message"""

print("Welcome") #print() function is used as a output function in python


Operators in Python:
Operators are the constructors that are used to manipulate the values of operands.
Example: a=10
b = 20
c = a+b
c= 30
Python supports different types of operators which are as follows
• Arithmetic operators
• Comparison Operator(Relational Operator)
• Assignment Operator
• Unary Operators
• Logical Operators
• Membership Operators
• Identity Operators
• Bitwise Operators
Arithmetic operators:
• Some basic arithmetic operators are +,-,*,/,%,** and //
• We can apply these operators in numbers as well as variables to perform corresponding
operations
• Let a= 10, b= 20

Operator Description Example Output

+ It is used to perform addition operation (add the operands) a+b 30

- Perform substation operation (subtract the operands) a-b -10

* Perform the multiplication operation a*b 200

/ It returns quotient a/b 0.5

% It returns the reminder b%a 0

** Perform power calculation(Exponent) a**b 1020

// Floor division a//b 20

Example:
a = float (input (“enter a number”))
b= float (input (“enter b value “))
print (“Addition of “,a,” and “, b,” is “,a+b)
print (“Subtraction of “,a,” and “,b,” is “,a-b)
print(“Product of “,a,” and “,b,” is “,a*b)
print (“Division of “,a,” and “,b,” is “,a/b)
print(“Modulus division of “,b,” and “,a,” is “,b%a)
print(“Floor division of “,a,” and “,b,” is “,a//b)
print(“Exponent of “,a,” and “,b,” is “,a**b)
Comparison Operator: (Relational Operators):
• It is used to compare the values on its either sides (Left and Right) of the operator and
determines the relation between them.
• Let a = 100, b = 200

Operator Description Example Output

== It returns true if the two values on either side of the operator a==b FALSE
are exactly same

!= It returns true if the two values on either side of the operator a!=b TRUE
are not same

< It returns true if the value at LHS of the operator is less than a<b TRUE
the value at the RHS of the operator, otherwise false

> It returns true if the value at LHS of the operator is greater a>b FALSE
than the value at the RHS of the operator, otherwise false

<= It returns true if the value at LHS of the operator is less than a<=b TRUE
or equal to the value at the RHS of the operator, otherwise
false

>= It returns true if the value at LHS of the operator is greater a>=b FALSE
than or equal to the value at the RHS of the operator,
otherwise false

Example:
a = float(input(“Enter the value of a: “))
b = float(input(“Enter the value of b: “))
print(a,” == “,b,a==b)
print(a,” != “,b,a!=b)
print(a,” < “,b,a<b)
print(a,” > “,b,a>b)
print(a,” <= “,b,a<=b)
print(a,” >= “,b,a>=b)
Assignment and In place OR shortcut operators
Assignment Operator: It is used to assign a value to the operand.

Syntax: variablename=value
variablename=Expression

Example 1 : a=10 Example 2: c=a+b


b=20 c=30

In place Operator:
In place operators are called as shortcut operators that includes +=,-=, *=, /=, %=, //=, **= allow
you to write code like num = num + 10 more concisely as num+ = 3
Operator Description Example
= Assign right side value to the left hand side variable a=b
+= Add and assign a+=b=> a=a+b
-= Subtract and assign a-=b=> a=a-b
*= Multiply and assign a*=b=> a=a*b
/= Divide and assign a/=b=> a=a/b
%= Modulus and assign a%=b=> a=a%b
//= Floor division and assign a//=b=> a=a//b
**= Exponent and assign a**=b=> a=a**b
Example:
str1 = “Good ”
str2 = “Morning”
str1+str2

Output: Good Morning


Unary Operators: ( -,+,~)
• Acts on single operand
• Python supports single minus (-)
• When an operand is preceded by a minus sign, the unary operator negates its value.
Example: b=10
print(-b)
Logical Operators:
• Logical operators are used to evaluate two or more expressions with relational operators.
• Python supports 3 logical Operators
1. Logical AND (and)
2. Logical OR (or)
3. Logical NOT (not)
Logical AND (and): If expression on both sides of the logical operator are true, then the whole
expression is true.
Truth Table:

Exp 1 Exp 2 Exp 1 and Exp2

T T T

T F F

F T F

F F F

Example:
Let a = 10, b = 20, c = 30, d = 40
(a<d) and (b>c)
(True) && (False)
Result = False
Logical OR (or): If one or both the expressions is true then the whole expression is true.
Truth Table:

Exp 1 Exp 2 Exp 3

T T T

T F T

F T T

F F F

Example: Let a = 10, b = 20, c = 30, d = 40


(a<d) and (b>c)
(True) and (False)
Result = True
Logical NOT (not):

• Logical NOT operator takes a single expression and negates the value of expression.
• Logical NOT produces a zero if the expression evaluates to a non-zero and produces 1 if the
expression produces zero.
Truth Table:

Expression !(Expression)

T (1) F (0)

F (0) T (1)

Example: Let a = 10, b = 20


not (a>b)
not (False)
Result : True

Bitwise Operators: Bitwise Operators perform operations at bit level. These operators include
1. Bitwise AND (&)
2. Bitwise OR (|)
3. Bitwise NOT (~)
4. Bitwise XOR (^)
5. Bitwise Shift
Bitwise operators expect their operands to be of integers and track them as a sequence of bits.
Bitwise AND (&):
The bit in the first operand is Anded with the corresponding bit in the second operand. If both
the bits are 1 then the corresponding bit result is 1 and 0 otherwise.
Truth Table:

Bit1 Bit2 Bit1 & Bit2

1 1 1

1 0 0

0 1 0

0 0 0

Example:
1010101010
&
1111010101
1010000000

Bitwise OR (|):
The bit in the first operand is Ored with the corresponding bit in the second operand. If either
of the bits are 1 then the corresponding bit result is 1 and 0 otherwise.
Truth Table:

Bit1 Bit2 Bit1 & Bit2

1 1 1

1 0 1

0 1 1

0 0 0

Example:
1010101010
|
1111010101
1111111111
Bitwise XOR (^):
The bit in the first operand is XORed with the corresponding bit in the second operand. If one
of the bits is 1, then the corresponding bit result is 1 otherwise 0
Truth Table:

Bit1 Bit2 Bit1 & Bit2

1 1 0

1 0 1

0 1 1

0 0 0

Example:
1010101010
^
1111010101
0101111111

Bitwise NOT (~):


It is a unary operation, which performs logical negation on each bit of the operand. It produces
1’s compliment of the given value
Truth Table:

Bit ~(Bit)

0 1

1 0

Example:
~ (1 0 1 0 1 0 1 0) = 0 1 0 1 0 1 0 1
Shift Operators:

• Python supports two bitwise shift operators


1. Shift Left (<<)
2. Shift Right (>>)
• These operators are used to shift bits to the left or right.
• Syntax of shift operation is operand op num
• Let x = 00011010

0 0 0 1 1 0 0 1
X
LSB MSB
• Example 1: shift Left
x=3
x<<2

0 0 0 1 1 0 0 1

0
0 0 1 1 0 0 1 0 Vacant space is filled with zero

0 0 1 1 0 0 1 0 0 Vacant space is filled with zero

• Example 1: shift Right


x=3
x>>2

0 0 0 0 0 0 1 1
1

0 0 0 0 0 0 0 1
Vacant space is filled 1
with zero

Vacant space is filled 0 0 0 0 0 0 0 0


with zero

Membership Operators:
Python supports two types of membership operators

• in

• not in
The names itself suggests that, test for membership in a sequence such as string, list, tuple.
In – The operator returns true if a variable is found in the specified sequence and false otherwise.
Example: a in nums - it returns one if ‘a’ is present in the nums
not in – The operator returns true if a variable is not found in the sequence.
Example: a not in nums - it returns 1 if ‘a’ is not present in the nums
Identity Operators:
These operators compare the memory locations of two objects. Python supports two types of
Identity Operators
Is operator: It returns true if operands (or) values on both sides of the operator point to the same
object and False otherwise.
Example: If a is b – it returns 1 if id (a) is same as id (b)
is not operator : It returns true if operands (or) values on both sides of the operator do not point to
the same object and False otherwise.
Example: If a is b – it returns 1 if id (a) is not same as id (b)
Operator Precedence and Associativity:
The following table is the list from higher precedence to lower precedence.

** Exponentiation

~, +, - Unary Operator

*, /, //, % Multiply, division, floor division, modulus division

+, - Addition and subtraction

>>, << Right and left bitwise shift operator

& Bitwise AND

^, | Bitwise XOR and regular OR

<=, >=, <, > Comparison operator

<>, ;, ==, != Equality operator

=, %=, +=, -= Assignment operators

Is, is not Identity operators

In, not in Membership operators

NOT, OR, AND Logical Operators

Expressions in Python:
• An expression is any logical combination of symbols (like variables, constants and operators)
that represent a value.
• Every language has some set of rules to define whether the expression is valid/invalid.
• In python, an expression must have at least have one operand can have one or more operators.

Example: a+b*c-5

In above expression
“ +, *, - “ are operators
“ a, b, c ” are operators
“ 5 “ is operators
• Valid Expression:

x = a/b
y = a*b
z = a^b
x = a>b
• Invalid Expressions: a+<y++

Types of Expression:

Python supports different types of expressions that can be classified as follows

• Based on position of operators in an expression


• Based on the datatype of the result obtained on evaluating an expression

Based on position of operators in an expression

These type of expressions include:

Infix expression: In this type of expression the operator is placed in between the operands

Example: a=b-c

Prefix expression: In this type of expression the operator is placed before the operands

Example: a=-bc

Post fix expression: In this type of expression the operator is placed after the operands

Example: a=bc-

Based on the data type of the result obtained on evaluating an expression:

These type of expressions include:

Constant Expression: This type of expression involves only constants.


Example: 8+9-2
Floating Point Expression: This type of expression produces floating point results
Example: a = 10, b = 5
a*b/2
Integer Expression: This type of expression produces integer result after evaluating the expression.
Example: a = 10
b=5
c = a*b
Relational Operator: This type of expression returns either true or false
Example: c = a>b
Result: True
Logical Expression:This type of expression combines two or more relational expressions and return a
value as true or false
Example: (a>b) and (a!=b)
False and True
Result:True
Bitwise Expressions:
This type of expressions manipulate data at bit level.
Example: x = y&z
Assignment Expression: In this type expression will assign a value or expression to a variable
Example: c=a+b
c=10

Data types in Python: In Python, Variables can store data of different types. Python supports the
following data types:

Python has some standard data types :


• Numbers(int,float,complex)
• String(str)
• Booleans(bool)
• List(list)
• Tuple(tuple)
• Sets(set)
• Dictionary(dict)
• Bytes and byte arrays
Numbers: It consist of following data types.
• Integers: Any whole value
Example: -1, 0, 1, -2
• Long integer: Bigger whole number
Example: 900000000000000001
• Note : There is no limit for size of integer in python
• Floating point integer: All the decimal numbers are floating point integers.
Example: 9.45, 3.14
• Complex: Numbers of ‘a+bj’ form are complex numbers
Example: 9+10j
Example:
>>> a=10
>>> type(a)
<class 'int'>
>>> b=2.65
>>> type(b)
<class 'float'>
>>> c=10+2j
>>> type(c)
<class 'complex'>
Boolean:

• Boolean is another data type in python.


• A variable of Boolean type can have one of the two values
o True
o False
• Similar to other variables, the Boolean variables are also created while we assign a value to them
or when we use relational operators on them
Example:
>>> status=True
>>> type(status)
<class 'bool'>
>>> status=False
>>> type(status)
<class 'bool'>
String:
• String is a sequence of characters enclosed by either single or double or triple quotation marks.
Example:
Single quote: ‘Hai’
Double quote: “Hello, hay ACET”
Triple quote: “’ My name is Aditya.I am studying in ACET.
I live in Rajahmundry”’
Example:
>>> s="aditya"
>>> type(s)
<class 'str'>
>>> s='aditya'
>>> type(s)
<class 'str'>
>>> s='''aditya'''
>>> type(s)
<class 'str'>
List:
• Ordered sequence
• Holds python object in a sequence.
• It is a sequence in which elements are written as a list of comma separated values between
square brackets.
• It is a versatile data type in python
Creating a List:
Syntax: List_name=[ item1, item2, …………… item n]
Example:
>>> l=[10,20,30,40,50]
>>> type(l)
<class 'list'>
>>> l=[1238,"raju",98.5]
>>> type(l)
<class 'list'>
Tuple:
Tuple is just like a list but differ in two things
• Immutable (we cant change a tuple)
• It uses parenthesis
Tuple creation syntax
tuple_name=(element 1, element2, ………………)
tuple_name=()
Example:
>>> t=(10,20,30,40,50)
>>> type(t)
<class 'tuple'>

Tuple Operations:

set: A set is mutable and an unordered collection of items with no duplicate values.

Syntax: set_name={item1,item2, item3 …}

Example:
>>> s={10,20,30,40,50,10,50,20}
>>> s
{40, 10, 50, 20, 30}
>>> type(s)
<class 'set'>
Set operations:
• Length
• Membership
• Concatenation
• Min()
• Max()
• Sorted()
• comparision
Set Methods:
• add()
• update()
• remove()
• pop()
• discard()
• clear()
• issubset()
• issuperset()
• union()
• intesection()
Dictinaory:
• A dictionary is an unordered set of key-value pair.
• Each key is separated from its value by a colon (:), and consecutive items are separated by
commas.
• The entire items in a dictionary are enclosed in curly brackets ({ }).
Syntax: dictionary_name= {‘key1’:’value1’, ‘key2’:’value2’,………..}
Example: airports={'LHR':'Hearthrow',
'LAX':'Los angeles',
'SIN':'Changi',
'FRA':'Frankfrut',
'ORD':'O hare',
'BOM':'Chhatrapati shivaji‘ }

Type Conversion:
Process of Converting one type of object into another type of object.the following are predefined
functions used for type conversion.
• int()
• float()
• complex()
• str()
• ord()
• hex()
• oct()
• bin()
• list()
• tuple()
• set()
• dict()
Example:
>>> int(12.6)
12
>>> float(2)
2.0
>>> complex(1,2)
(1+2j)
>>> str(12)
'12'
>>> oct(123)
'0o173'
>>> bon(15)
>>> bin(15)
'0b1111'
>>> hex(37)
'0x25'
>>> ord('c')
99
Using Functions and modules:
Function:
A function is a block of code which which perform specific task.
Module:
A module is collection of variables, functions and classes.
Types of functions:
1. Built-in (or) Pre-defined functions
print(),input()

2. User-defined functions
Functions which are defined by user
Predefined function inside a module can be accessed using import statements.
Syntax 1: (This syntax will import all the functions inside a module)
import module-name
Example
import math
print(math.sqrt(25))
Syntax 2: (This syntax will import only specified functions inside a module)
from module-name import functions
Example:
from math import sqsssrt
print(math.sqrt(25))

You might also like