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

Python (Module-I)

The document provides an overview of Python programming, explaining what a program is, the differences between compilers and interpreters, and the features of Python. It covers Python's history, naming origin, and key concepts such as comments, keywords, identifiers, variables, and data types. Additionally, it highlights Python's ease of use, expressiveness, and cross-platform capabilities.

Uploaded by

Arjun Sinha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python (Module-I)

The document provides an overview of Python programming, explaining what a program is, the differences between compilers and interpreters, and the features of Python. It covers Python's history, naming origin, and key concepts such as comments, keywords, identifiers, variables, and data types. Additionally, it highlights Python's ease of use, expressiveness, and cross-platform capabilities.

Uploaded by

Arjun Sinha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Python Programming

What is a Program?
A computer program is a collection of instructions that can be executed by
a computer to perform a specific task.
A computer program is usually written by a computer p r ogrammer in a
programming language. From the program in its human-readable form of source
code, a compiler or assembler can derive machine code—a form consisting of
instructions that the computer can directly execute. Alternatively, a computer
program may be executed with the aid of an interpreter.

Difference between Compiler and Interpreter


1. Compiler:
It is a translator which takes input i.e., High-Level Language, and produces an
output of low-level language i.e. machine or assembly language.
 A compiler is more intelligent than an assembler it checks all kinds of limits,
ranges, errors, etc.
 But its program run time is more and occupies a larger part of memory. It
has a slow speed because a compiler goes through the entire program and then
translates the entire program into machine codes.

2. Interpreter:
An interpreter is a program that translates a programming language into a
comprehensible language. –
 It translates only one statement of the program at a time.
 Interpreters, more often than not are smaller than compilers.
S.No. Compiler Interpreter

1 Compiler scans the whole program Translates program one statement


in one go. at a time.

2 As it scans the code in one go, the Considering it scans code one line at
errors (if any) are shown at the a time, errors are shown line by line.
end together.

3 Main advantage of compilers is it’s Due to interpreters being slow in


execution time. executing the object code, it is
preferred less.

4. It converts the source code into It does not convert source code into
object code. object code instead it scans it line
by line

5 It does not require source code It requires source code for later
for later execution. execution.

6 C, C++, C# etc. Python, Ruby, Perl, SNOBOL,


MATLAB, etc.

Introduction to Python Programming


 Python is a general-purpose, interpreted, interactive, object-oriented,
modular and high-level programming language.
 High level language will be in human readable form and are easy to write as
well as compile or interpret.
 An interpreted language is a type of programming language that execute
instructions directly and freely, without previously compiling a program into
machine-language instructions.
 Interactive mode is a command line shell which gives immediate feedback for
each statement.
 Object-oriented programming is a programming paradigm based on the
concept of "objects", which can contain data, in the form of fields, and code,
in the form of procedures(methods).variables are also known as fields,
members, attributes, or properties.
 Modular programming is the process of subdividing a computer program into
separate sub- programs.
 All scripting languages are programming languages. The scripting language is
basically a language where instructions are written for a run time
environment. They do not require the compilation step and are rather
interpreted. Eg: python, php
 These languages can fulfil more than one purpose, for example they can be
apt for mathematical calculations, research work and application development
at the same time.

Python History
 Python was developed by Guido van Rossum in the late eighties and early

nineties at the National Research Institute for Mathematics and Computer

Science in the Netherlands.

 Python is derived from many other languages, including ABC, Modula-3, C,

C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.

 Python is copyrighted. Like Perl, Python source code is now available under

the GNU General Public License (GPL).

 Python is now maintained by a core development team at the institute,

although Guido van Rossum still holds a vital role in directing its progress.

Why the Name Python?

There is a fact behind choosing the name Python. Guido van Rossum was reading
the script of a popular BBC comedy series "Monty Python's Flying Circus". It
was late on-air 1970s.

Van Rossum wanted to select a name which unique, sort, and little-bit
mysterious. So he decided to select naming Python after the "Monty Python's
Flying Circus" for their newly created programming language.

The comedy series was creative and well random. It talks about everything.
Thus it is slow and unpredictable, which made it very interesting.

Features of Python
 Easy to Learn and Use: Python is easy to learn and use. It is developer-
friendly and high-level programming language.
 Expressive Language: Python language is more expressive means that it is
more understandable and readable.
 Interpreted Language: Python is an interpreted language i.e. interpreter
executes the code line by line at a time. This makes debugging easy and thus
suitable for beginners.
 Cross-platform Language: Python can run equally on different platforms such
as Windows, Linux, Unix and Macintosh etc. So, we can say that Python is a
portable language.
 Free and Open Source: Python language is freely available at official web
address. The source code is also available. Therefore, it is open source.
 Object-Oriented Language: Python supports object-oriented language and
concepts of classes and objects come into existence.
 Extensible: It implies that other languages such as C/C++ can be used to
compile the code and thus it can be used further in our python code.
 Large Standard Library: Python has a large and broad library and provides a
rich set of modules and functions for rapid application development.
 GUI Programming Support: Graphical user interfaces can be developed using
Python.
 Integrated: It can be easily integrated with languages like C, C++, JAVA, etc.
 Platform independent: Write once and run anywhere
 Dynamically typed Language: We cannot require specifying the data type
explicitly. Dynamically typed language provides more flexibility to the
programmer. We are not fixed the type of the variable.

Python comments
 A comment is text that doesn’t affect the outcome of a code; it is just
a piece of text to let someone know what you have done in a program or what
is being done in a block of code.
 This is especially helpful when someone else has written a code and you are
analyzing it for bug fixing or making a change in logic, by reading a comment
you can understand the purpose of code much faster than by just going
through the actual code.
Types of Comments in Python
There are two types of comments in Python.
1. Single-line comment
2. Multiple-line comment
Single line comment
 In python we use # special character to start the comment. Let’s take few
examples to understand the usage.
# This is just a comment. Anything written here is ignored by Python

Multi-line comment:
 To have a multi-line comment in Python, we use triple single quotes at the
beginning and at the end of the comment, as shown below.
'''
This is a
multi-line
comment
'''

Python Comments Example


 In this Python program we are seeing three types of comments. Single line
comment, multi-line comment and the comment that is starting in the same
line after the code.
'''
We are writing a simple program here
First print statement.
This is a multiple line comment.
'''
print("Hello Guys")

# Second print statement


print("How are You all?")

print("Welcome to BeginnersBook") # Third print statement


Python Keywords
 Python Keywords are special reserved words that convey a special meaning to
the compiler/interpreter.
 Each keyword has a special meaning and a specific operation. These keywords
can't be used as a variable.
 The Python Keywords are
True False class def return

if elif else try except

raise finally for in is

not from import global lambda

nonlocal pass while break continue

and with as yield del

or assert None
 We can get the list of keywords in your current version by typing the
following in the prompt.
>>> help("keywords")
(or)
>>> import keyword
>>> print(keyword.kwlist)
Python Identifiers
 An identifier is a name given to entities like class, functions, variables, etc.

Rules for writing identifiers


1. Identifiers can be a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore _.
2. An identifier cannot start with a digit.
3. Keywords cannot be used as identifiers.
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
5. An identifier can be of any length.

Valid Identifiers:
Names like myClass, var_1 and print_this_to_screen, all are valid example.
Invalid Identifiers:
1variable is invalid
global is invalid
ab@ is invalid

Things to Remember
 Python is a case-sensitive language. This means, Variable and variable are not
the same.
 Always give the identifiers a name that makes sense. While c = 10 is a valid
name, writing count = 10 would make more sense, and it would be easier to
figure out what it represents when you look at your code after a long gap.
 Multiple words can be separated using an underscore,
like this_is_a_long_variable.
Variable
 Variables are nothing but reserved memory locations to store values. It
means that when you create a variable, you reserve some space in the
memory.
 Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning
different data types to the variables, you can store integers, decimals or
characters in these variables.

Rules for creating variables in Python:


1. A variable name must start with a letter or the underscore character.
2. A variable name cannot start with a number.
3. A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
4. Variable names are case-sensitive (name, Name and NAME are three
different variables).
5. The reserved words(keywords) cannot be used naming the variable.
6. Special symbols and white space are not used as variable name.

Assigning Values to Variables


 Python variables do not need explicit declaration to reserve memory space.
 The declaration happens automatically when you assign a value to a variable.
 The equal sign (=) is used to assign values to variables.
 The operand to the left of the = operator is the name of the variable and the
operand to the right of the = operator is the value stored in the variable.

Example −
#!/usr/bin/python3

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

print (counter)
print (miles)
print (name)
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and
name variables, respectively.
This produces the following result −
100
1000.0
John
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
For example −
a = b = c = 1
Here, an integer object is created with the value 1, and all the three variables
are assigned to the same memory location.
You can also assign multiple objects to multiple variables.
For example −
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to the variables a
and b respectively, and one string object with the value "john" is assigned to the
variable c.
Input/output Statements
Python input( ) function
 The input() method reads a line from input, converts into a string and returns
it.

Syntax
input(prompt)
prompt(optional) → A String, representing a default message before the input.
Examples
>>> x = input()
2
>>> x
'2'
>>> x1 = input("Enter a String")
Enter a String 2
>>> x1
' 2'
>>> y = int(input("Enter a number"))
Enter a number2
>>> y
2
>>> y1 = float(input("Enter a floating value"))
Enter a floating value 2.5
>>> y1
2.5

Python print()
 The print() function prints the given object to the standard output device
(screen) or to the text stream file.
Syntax of print()
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

print() Parameters
 objects - object to the printed. * indicates that there may be more than one
object
 sep - objects are separated by sep. Default value: ' '
 end - end is printed at last
 file - must be an object with write(string) method. If omitted
it, sys.stdout will be used which prints objects on the screen.
 flush - If True, the stream is forcibly flushed. Default value: False

Examples:
>>> print("Hello","world")
Hello world
>>> print("hello","world",sep="")
helloworld
>>> print("hello","world",sep="-")
hello-world
>>> print(192,168,17,1,sep=".")
192.168.17.1
print_st.py
print("Welcome to python",end=" ")
print("programming")
output
Welcome to python programming

print() with file parameter


In Python, you can print objects to the file by specifying
the file parameter.
Example
>>> f = open("d:\hari.txt", "w")
>>> print("welcome to python", file = f)
>>> print("programming", file = f, flush=True)
>>> f.close()

Python indentation
 Python indentation uses to define the block of the code. The other
programming languages such as C, C++, and Java use curly braces {}, whereas
Python uses an indentation. Whitespaces are used as indentation in Python.
 Indentation uses at the beginning of the code and ends with the unintended
line. That same line indentation defines the block of the code (body of a
function, loop, etc.)
 Generally, four whitespaces are used as the indentation. The amount of
indentation depends on user, but it must be consistent throughout that block.

for i in range(5):
print(i)
if(i == 3):
break

 To indicate a block of code we indented each line of the block by the same
whitespaces.
Consider the following example.

dn = int(input("Enter the number:"))


if(n%2 == 0):
print("Even Number")
else:
print("Odd Number")

print("Task Complete")

Output:

Enter the number: 10


Even Number
Task Complete

 The above code, if and else are two separate code blocks. Both code blocks
are indented four spaces. The print("Task Complete") statement is not
indented four whitespaces and it is out of the if-else block.
 If the indentation is not used properly, then that will result
in IndentationError.

Data types

 Variables can hold values, and every value has a data-type.


 Python is a dynamically typed language; hence we do not need to define the
type of the variable while declaring it.
 The interpreter implicitly binds the value with its type.

a = 5

 The variable ‘a’ holds integer value five and we did not define its type.
 Python interpreter will automatically interpret variables a as an integer type.
 Python enables us to check the type of the variable used in the program.
 Python provides us the type() function, which returns the type of the
variable passed.

Example

a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))

Output:

<class 'int'>
<class 'str'>
<class 'float'>

Data types are the classification or categorization of data items. Python


supports the following built-in data types.

S. No Name of Data Type Keywords

1 Numeric Types: int, float, complex

2 Sequence Types: str,list, tuple, range

3 Mapping Type: dict

4 Set Types: set, frozenset

5 Boolean Type: bool

Number Types: int, float, complex


Python includes three numeric types to represent numbers: integers, float, and
complex number.
Int
In Python, integers are zero, positive or negative whole numbers without a
fractional part and having unlimited precision, e.g. 0, 100, -10. The followings are
valid integer literals in Python.
>>> 0
0
>>> 100
100
>>> -10
-10
>>> 1234567890
1234567890
>>> y=5000000000000000000000000000000000000000000000000000000
5000000000000000000000000000000000000000000000000000000

Integers can be binary, octal, and hexadecimal values.

>>> 0b11011000 # binary


216
>>> 0o12 # octal
10
>>> 0x12 # hexadecimal
18

All integer literals or variables are objects of the int class. Use
the type() method to get the class name, as shown below.

>>>type(100)
<class 'int'> # type of x is int

>>> x=1234567890
>>> type(x)
<class 'int'> # type of x is int

>>> y=5000000000000000000000000000000000000000000000000000000
>>> type(y) # type of y is int
<class 'int'>

Leading zeros in non-zero integers are not allowed e.g. 000123 is invalid number,
0000 is 0.

>>> x=01234567890
SyntaxError: invalid token

Python does not allow comma as number delimiter. Uses underscore _ as a


delimiter instead.

>>> x=1_234_567_890
>>> x
1234567890

Note that integers must be without a fractional part (decimal point). It includes
a fractional then it becomes a float.
>>> x=5
>>> type(x)
<class 'int'>
>>> x=5.0
>>> type(x)
<class 'float'>

The int() function converts a string or float to int.

>>> int('100')
100
>>> int('-10')
-10
>>> int('5.5')
5
>>> int('100', 2)
4

Binary
A number having 0b with eight digits in the combination of 0 and 1 represent
the binary numbers in Python. For example, 0b11011000 is a binary number
equivalent to integer 216.
>>> x=0b11011000
>>> x
216
>>> x=0b_1101_1000
>>> x
216
>>> type(x)
<class 'int'>

Octal
 A number having 0o or 0O as prefix represents an octal number. For example,
0O12 is equivalent to integer 10.
>>> x=0o12
>>> x
10
>>> type(x)
<class 'int'>

Hexadecimal
 A number with 0x or 0X as prefix represents hexadecimal number.
For example, 0x12 is equivalent to integer 18.
>>> x=0x12
>>> x
18
>>> type(x)
<class 'int'>

Float
 In Python, floating point numbers (float) are positive and negative real
numbers with a fractional part denoted by the decimal symbol or the
scientific notation E or e,
 Example: 1234.56, 3.142, -1.55, 0.23.

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

 Floats can be separated by the underscore _,


 Example: 123_42.222_013 is a valid float.

>>> f=123_42.222_013
>>> f
12342.222013

 Floats has the maximum size depends on your system.


 The float beyond its maximum size referred as "inf", "Inf", "INFINITY", or
"infinity".
 Float 2e400 will be considered as infinity for most systems.

>>> f=2e400
>>> f
inf

 Scientific notation is used as a short representation to express floats having


many digits.
 Example: 345.56789 is represented as 3.4556789e2 or 3.4556789E2

>>> f=1e3
>>> f
1000.0
>>> f=1e5
>>> f
100000.0
>>> f=3.4556789e2
>>> f
345.56789

 Use the float() function to convert string, int to float.

>>> float('5.5')
5.5
>>> float('5')
5.0
>>> float(' -5')
-5.0
>>> float('1e3')
1000.0
>>> float('-Infinity')
-inf
>>> float('inf')
inf

Complex Number
 A complex number is a number with real and imaginary components.
 Example: 5 + 6j is a complex number where 5 is the real component and 6
multiplied by j is an imaginary component.

>>> a=5+2j
>>> a
(5+2j)
>>> type(a)
<class 'complex'>

 You must use j or J as imaginary component. Using other character will throw
syntax error.

>>> a=5+2k
SyntaxError: invalid syntax
>>> a=5+j
SyntaxError: invalid syntax
>>> a=5j+2j
>>> a
7j

Sequence types
 A sequence is a group of items with a deterministic ordering.
String
 In Python, string is an immutable sequence data type.
 It is the sequence of Unicode characters wrapped inside single, double, or
triple quotes.

'This is a string in Python' # string in single quotes


"This is a string in Python" # string in double quotes
'''This is a string in Python''' # string in triple quotes
"""This is a string in Python""" # string in triple double-quotes

 A string literal can be assigned to a variable.

str1='This is a string in Python'


print(str1)
str2="This is a string in Python"
print(str2)
Output:

This is a string in Python


This is a string in Python

Multi-line strings must be embedding in triple quotes.

str1='''This is
the first
Multi-line string.
'''
print(str1)

str2="""This is
the second
Multi-line
string."""
print(str2)

Output:

This is
the first
Multi-line string.

This is
the second
Multi-line
string.
If a string literal required embedding double quotes as part of a string then, it
should be put in single quotes. Likewise, if a string includes a single quote as a
part of a string then, it should be written in double quotes.

str1='Welcome to "Python Tutorial" on Tutorials'


print(str1)

str2="Welcome to 'Python Tutorial' on Tutorials"


print(str2)

Output:

Welcome to "Python Tutorial" from Tutorials


Welcome to 'Python Tutorial' on Tutorials

Use the len() function to retrieve the length of a string.

>>> greet='Hello'
>>> len(greet)
5

The sequence uses an index, starting with zero to fetch a certain item (a
character in case of a string) from it.

Positive Indexing 0 1 2 3 4
H e l l o
Negative Indexing -5 -4 -3 -2 -1
>>> greet='hello'
>>> greet[0]
'h'
>>> greet[1]
'e'
>>> greet[2]
'l'
>>> greet[3]
'l'
>>> greet[4]
'o'
>>> greet[5] # throw error if index > len(string)-1
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
greet[5]
IndexError: string index out of range

Python supports negative indexing too, starting with -(length of string) till -1.
>>> greet='hello'
>>> greet[-5]
'h'
>>> greet[-4]
'e'
>>> greet[-3]
'l'
>>> greet[-2]
'l'
>>> greet[-1]
'o'

The string is an immutable object. Hence, it is not possible to modify it. The
attempt to assign different characters at a certain index results in errors.

>>> greet='hello'
>>> greet[0]='A'
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
greet[0]='A'
TypeError: 'str' object does not support item assignment

str Class

All strings are objects of the str class in Python.

>>> greet='hello'
>>> type(greet)
<class 'str'>

Use the str() function to convert a number to a string.

>>> str(100)
'100'
>>> str(-10)
'-10'
>>> str(True)
'True'

Escape Sequences

The escape character is used to invoke an alternative implementation of the


subsequent character in a sequence.

In Python, backslash \ is used as an escape character.


Use a backslash character followed by the character you want to insert in a
string Example. \' to include a quote, or \" to include a double quotes in a string,
as shown below.

str1='Welcome to \'Python Tutorial\' on Tutorials'


print(str1)

str2="Welcome to \"Python Tutorial\" on Tutorials"


print(str2)

Output:

Welcome to 'Python Tutorial' from Tutorials


Welcome to "Python Tutorial" on Tutorials

Use r or R to ignore escape sequences in a string.

str1=r'Welcome to \'Python Tutorial\' on Tutorials'


print(str1)

Output:

Welcome to \'Python Tutorial\' from Tutorials

The following table lists escape sequences in Python.

Escape sequence Description Example

\\ Backslash >>> "Hello\\Hi"


Hello\Hi

\b Backspace >>> "ab\bc"


ac

\f Form feed

\n Newline >>> "hello\nworld"


Hello
world

\nnn Octal notation, >>> '\101'


where n is in the A
range 0-7

\t Tab >>> 'Hello\tPython'


Hello Python
Escape sequence Description Example

\xnn Hexadecimal >>> '\x48\x69'


notation, where n is Hi
in the range 0-9, a-
f, or A-F

List

In Python, the list is a mutable sequence type. A list object contains one or
more items of different data types in the square brackets [] separated by a
comma.

mylist=[] # empty list


print(mylist)

names=["Jeff", "Bill", "Steve", "Mohan"] # string list


print(names)

item=[1, "Jeff", "Computer", 75.50, True] # list with heterogeneous


data
print(item)

A list can contain unlimited data depending upon the limitation of your
computer's memory.
nums=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60]

List items can be accessed using a zero-based index in the square brackets [].
Indexes start from zero and increment by one for each item. Accessing an item
using a large index than the list's total items would result in IndexError.

names=["Jeff", "Bill", "Steve", "Mohan"]


print(names[0]) # returns "Jeff"
print(names[1]) # returns "Bill"
print(names[2]) # returns "Steve"
print(names[3]) # returns "Mohan"
print(names[4]) # throws IndexError: list index out of range

Negative Indexing
names = ['Jeff', 'Bill', 'Steve', 'Yash']
print(names[-4]) # prints 'Jeff'
print(names[-3]) # prints 'Bill'
print(names[-2]) # prints 'Steve'
print(names[-1]) # prints 'Yash'

A list can contain multiple inner lists as items that can be accessed using
indexes.

nums=[1, 2, 3, [4, 5, 6, [7, 8, [9]]], 10]


print(names[0]) # returns 1
print(names[1]) # returns 2
print(names[3]) # returns [4, 5, 6, [7, 8, [9]]]
print(names[4]) # returns 10
print(names[3][0]) # returns 4
print(names[3][3]) # returns [7, 8, [9]]
print(nums[3][3][0]) # returns 7
print(nums[3][3][2]) # returns [9]

List Class

All the list objects are the objects of the list class in Python. Use
the list() constructor to convert from other sequence types such as tuple, set,
dictionary, string to list.
nums=[1,2,3,4]
print(type(nums))

mylist=list('Hello')
print(mylist)

nums=list({1:'one',2:'two'})
print(nums)

nums=list((10, 20, 30))


print(nums)

nums=list({100, 200, 300})


print(nums)

Output:
<class 'list'>
['H', 'e', 'l', 'l', 'o']
[1, 2]
[10, 20, 30]
[100, 200, 300]

Tuples

Tuple is an immutable (unchangeable) collection of elements of different data


types. It is an ordered collection, so it preserves the order of elements in which
they were defined.

Tuples are defined by enclosing elements in parentheses (), separated by a


comma.
Example:

tpl=() # empty tuple


print(tpl)

names = ('Jeff', 'Bill', 'Steve', 'Yash') # string tuple


print(names)

nums = (1, 2, 3, 4, 5) # int tuple


print(nums)

employee=(1, 'Steve', True, 25, 12000) # heterogeneous data tuple


print(employee)
Output:

()
('Jeff', 'Bill', 'Steve', 'Yash')
(1, 2, 3, 4, 5)
(1, 'Steve', True, 25, 12000)

However, it is not necessary to enclose the tuple elements in parentheses. The


tuple object can include elements separated by a comma without parentheses.
Example:

names = 'Jeff', 'Bill', 'Steve', 'Yash' # string tuple


print(names)

nums = 1, 2, 3, 4, 5 # int tuple


print(nums)

employee=1, 'Steve', True, 25, 12000 # heterogeneous data tuple


print(employee)
Output:

('Jeff', 'Bill', 'Steve', 'Yash')


(1, 2, 3, 4, 5)
(1, 'Steve', True, 25, 12000)

Tuples cannot be declared with a single element unless followed by a comma.


Example:

names = ('Jeff') # considered as string type


print(names)
print(type(names))

names = ('Jeff',) # tuple with single element


print(names)
print(type(names))
Output:

'Jeff'
<class 'string'>
(Jeff)
<class 'tuple'>
Access Tuple Elements
Each element in the tuple is accessed by the index in the square brackets []. An
index starts with zero and ends with (number of elements – 1).
Example:

names = ('Jeff', 'Bill', 'Steve', 'Yash')


print(names[0]) # prints 'Jeff'
print(names[1]) # prints 'Bill'
print(names[2]) # prints 'Steve'
print(names[3]) # prints 'Yash'

nums = (1, 2, 3, 4, 5)
print(nums[0]) # prints 1
print(nums[1]) # prints 2
print(nums[4]) # prints 5
Output:

Jeff
Bill
Steve
Yash
1
2
5

The tuple supports negative indexing also, the same as list type. The negative
index for the first element starts from -number of elements and ends with -1
for the last element.
Example: Negative Indexing

names = ('Jeff', 'Bill', 'Steve', 'Yash')


print(names[-4]) # prints 'Jeff'
print(names[-3]) # prints 'Bill'
print(names[-2]) # prints 'Steve'
print(names[-1]) # prints 'Yash'
Output:

Jeff
Bill
Steve
Yash

If the element at the specified index does not exist, then the error "index out
of range" will be thrown.
>>> names[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
Tuple elements can be unpacked and assigned to variables, as shown below.
However, the number of variables must match with the number of elements in a
tuple; otherwise, an error will be thrown.
Example: Access Tuple Elements using Indexes

names = ('Jeff', 'Bill', 'Steve', 'Yash')


a, b, c, d = names # unpack tuple
print(a, b, c, d)
Output:

Jeff Bill Steve Yash

Update or Delete Tuple Elements

Tuple is unchangeable. So, once a tuple is created, any operation that seeks to
change its contents is not allowed. For instance, trying to modify or delete an
element of names tuple will result in an error.
>>> names = ('Jeff', 'Bill', 'Steve', 'Yash')
>>> names[0] = 'Swati'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

>>> del names[0]


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion

However, you can delete an entire tuple using the del keyword.
>>> del names

Tuple Class
The underlying type of a tuple is the tuple class. Check the type of a variable
using the type() function.
Example:
names = ('Jeff', 'Bill', 'Steve', 'Yash')
print('names type: ', type(names))

nums = (1,2,3,4,5)
print('nums type: ', type(nums))
Output:
names type: <class 'tuple'>
nums type: <class 'tuple'>
The tuple() constructor is used to convert any iterable to tuple type.
Example:
tpl = tuple('Hello') # converts string to tuple
print(tpl)
tpl = tuple([1,2,3,4,5]) # converts list to tuple
print(tpl)
Output:
('H','e','l','l','o')
(1,2,3,4,5)

range() Method
The range() method returns the immutable sequence numbers between the
specified start and the stop parameter, increment by step parameter.
Syntax:
range(start, stop, step)
Parameters:
 start: (Optional) An integer to start counting from, defaults to 0.
 stop: An integer to stop the count at.
 step: (Optional) An integer that indicates the incremental value from start
parameter value, defaults to 1.
Return Value:
Returns an immutable sequence object of numbers.
Example: range()
num_range = range(5) #start=0, stop=5, step=1
print(type(num_range))
print(num_range)
print('Values = ', num_range[0], num_range[1], num_range[2],
num_range[3], num_range[4])
Output
<class 'range'>
range(0, 5)
Values = 0 1 2 3 4
In the above example, the range(5) returns the range object with the default
start 0, stop 5, and default step 1. The range is an immutable sequence, so that
values can be accessed by passing indexes in the square brackets [].
The in operator is used to check whether the particular number exists in the
range sequence or not, as shown below.
Example:
num_range = range(5) #start=0, stop=5, step=1
print(0 in num_range)
print(4 in num_range)
print(5 in num_range)
print(6 in num_range)
Output
True
True
False
False
The range object can be converted to the other iterable types such as list,
tuple, and set.
Example: Convert Range to other Iterables
print(list(range(5)))
print(tuple(range(5)))
print(set(range(5)))
Output
[0, 1, 2, 3, 4]
(0, 1, 2, 3, 4)
{0, 1, 2, 3, 4}
The following creates a different range objects with different values of start
and step parameters.
Example: range()
num_range1 = range(1, 5) #start=1, stop=5, step=1
print('range(1, 5) = ', list(num_range1))

num_range2 = range(1, 10, 2) #start=1, stop=10, step=2


print('range(1, 10, 2) = ', list(num_range2))

num_range3 = range(0, 20, 5) #start=0, stop=20, step=5


print('range(0, 20, 5) = ', list(num_range3))

num_range4 = range(-5, -1) #start=-5, stop=-1, step=1


print('range(-5, -1) = ', list(num_range4))

num_range5 = range(-5) #start=0, stop=-5, step=1


print('range(-5) = ', list(num_range5))
Output
range(1, 5) = [1, 2, 3, 4]
range(1,10, 2) = [1, 3, 5, 7, 9]
range(0, 20, 5) = [0, 5, 10, 15]
range(-5, -1) = [-5, -4, -3, -2]
range(-5) = []

Dictionary
The dictionary is an unordered collection that contains key:value pairs
separated by commas inside curly brackets. Dictionaries are optimized to
retrieve values when the key is known.

Example: Dictionary
capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New
Delhi"}
Above, capitals is a dictionary object which contains key-value pairs inside { }.
The left side of : is a key, and the right side is a value. The key should be unique
and an immutable object. A number, string or tuple can be used as key. Hence,
the following dictionaries are also valid:
Example: Dictionary Objects
d = {} # empty dictionary

numNames={1:"One", 2: "Two", 3:"Three"} # int key, string value

decNames={1.5:"One and Half", 2.5: "Two and Half", 3.5:"Three and


Half"} # float key, string value

items={("Parker","Reynolds","Camlin"):"pen",
("LG","Whirlpool","Samsung"): "Refrigerator"} # tuple key, string
value

romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5} # string key,


int value
Example: List as Dictionary Value
dict_obj = {"Fruit":["Mango","Banana"], "Color":["Blue", "Red"]}
The same key cannot appear more than once in a collection. If the key appears
more than once, only the last will be retained. The value can be of any data type.
One value can be assigned to more than one key.
Example: Unique Keys
>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}
>>> numNames
{1:"One", 2:"Two", 3:"Three"}
The dict is the class of all dictionaries, as shown below.
Example: Distinct Type
>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}
>>> type(numNames)
<class 'dict'>
Example: dict() Constructor Method
>>> emptydict = dict()
>>> emptydict
{}
>>> numdict = dict(I='one', II='two', III='three')
>>> numdict
{'I': 'one', 'II': 'two', 'III': 'three'}

Access Dictionary
Dictionary is an unordered collection, so a value cannot be accessed using an
index; instead, a key must be specified in the square brackets.
Example: Get Dictionary Values
>>> capitals = {"USA":"Washington DC", "France":"Paris",
"India":"New Delhi"}
>>>capitals["USA"]
'Washington DC'
>>> capitals["France"]
'Paris'
>>> capitals["usa"] # Error: Key is case-sensitive
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
capitals['usa']
KeyError: 'usa'
>>> capitals["Japan"] # Error: key must exist
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
capitals['Japan']
KeyError: 'Japan'

Note:
Keys are case-sensitive. So, usa and USA are treated as different keys. If the
specified key does not exist then it will raise an error.

Set
A set is a mutable collection of distinct hashable objects, same as
the list and tuple. It is an unordered collection of objects, meaning it does not
record element position or order of insertion and so cannot access elements
using indexes.
A set object contains one or more items, not necessarily of the same type,
which are separated by a comma and enclosed in curly brackets {}.
Example: Python Set Object
even_nums = {2, 4, 6, 8, 10} # set of even numbers
emp = {1, 'Steve', 10.5, True} # set of different objects

A set doesn't store duplicate objects. Even if an object is added more than
once inside the curly brackets, only one copy is held in the set object. Hence,
indexing and slicing operations cannot be done on a set object.
Example: Set of Distinct Elements
>>> nums = {1, 2, 2, 3, 4, 4, 5, 5}
>>> nums
{1, 2, 3, 4, 5}

The order of elements in the set is not necessarily the same as the order given
at the time of assignment. Python optimizes the structure of a set for
performing operations over it, as defined in mathematics.
Only immutable (and hashable) objects can be a part of a set object. Numbers
(integer, float, as well as complex), strings, and tuple objects are accepted, but
set, list, and dictionary objects are not.
Example: Set Elements
>>> myset = {(10,10), 10, 20} # valid
>>> myset
{10, 20, (10, 10)}
>>> myset = {[10, 10], 10, 20} # can't add a list
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
myset = {[10, 10], 10, 20}
TypeError: unhashable type: 'list'
>>> myset = { {10, 10}, 10, 20} # can't add a set
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
myset = { {10, 10}, 10, 20}
TypeError: unhashable type: 'set'

In the above example, (10,10) is a tuple, hence it becomes part of the set.
However, [10,10] is a list, hence an error message is displayed saying that the
list is unhashable. (Hashing is a mechanism in computer science which enables
quicker search of objects in the computer's memory.)
Even though mutable objects are not stored in a set, the set itself is a mutable
object.
Use the set() function to create an empty set. Empty curly braces will create an
empty dictionary instead of an empty set.
Example: Creating an Empty Set
>>> emp = {} # creates an empty dictionary
>>> type(emp)
<class 'dict'>
>>> s = set() # creates an empty set
>>> type(s)
<class 'set'>

The set() function also use to convert string, tuple, or dictionary object to a set
object.

Example: Convert Sequence to Set


>>> s = set('Hello') # converts string to set
>>> s
{'l', 'H', 'o', 'e'}
>>> s = set((1,2,3,4,5)) # converts tuple to set
>>> s
{1, 2, 3, 4, 5}
>>> d = {1:'One', 2: 'Two'}
>>> s = set(d) # converts dict to set
>>> s
{1, 2}

frozenset()
The python frozenset() function returns an immutable frozenset object
initialized with elements from the given iterable.
syntax
frozenset(iterable)
Parameters
iterable: An iterable object such as list, tuple etc.
Return
It returns an immutable frozenset object initialized with elements from the
given iterable.
Example
working of frozenset().
# tuple of letters
letters = ('m', 'r', 'o', 't', 's')

fSet = frozenset(letters)
print('Frozen set is:', fSet)
print('Empty frozen set is:', frozenset())
Output:
Frozen set is: frozenset({'o', 'm', 's', 'r', 't'})
Empty frozen set is: frozenset()

In the above example, we take a variable that consists tuple of letters and
returns an immutable frozenset object.

Example
working of frozenset() with dictionaries.
# random dictionary
person = {"name": "Phill", "age": 22, "sex": "male"}

fSet = frozenset(person)
print('Frozen set is:', fSet)

Output:
Frozen set is: frozenset({'name', 'sex', 'age'})

bool()
The bool() method converts a value to the bool class object containing either
True or False.
Syntax:
bool(value)
Parameters:
value: (Optional) The value to be converted to boolean.
Return Value:
Returns True for truthy value else returns False for falsy value 0, None or ''

Example:
value = [0]
print("Boolean of [0] is: ", bool(value))

value = 0
print("Boolean of 0 is: ", bool(value))

value = 1
print("Boolean of 1 is: ", bool(value))
value = -1
print("Boolean of -1 is: ", bool(value))

value = None
print("Boolean of None is: ",bool(value))

value = True
print("Boolean of True is: ", bool(value))

value = False
print("Boolean of False is: ", bool(value))

value = 'a string'


print("Boolean of a string is: ", bool(value))

Output
Boolean of [0] is: True
Boolean of 0 is: False
Boolean of 1 is: True
Boolean of -1 is: True
Boolean of None is: False
Boolean of True is: True
Boolean of False is: False
Boolean of a string is: True

Type Checking
Type Checking is the programming language feature that specifies how the
variables are created and their types are identified by the language compiler or
interpreter.
Python is a dynamically typed language. This means that the Python interpreter
does type checking only as code runs, and that the type of a variable is allowed
to change over its lifetime.
type()
 Python type() returns the type of the specified object if a single argument is
passed to the type().
Syntax
type(object)
Parameter
 The object argument is required, and it can be string,
integer, list, tuple, set, dictionary, float, etc.
Example
str = 'Hello'
print(type(str))
int = 123
print(type(int))
float = 21.19
print(type(float))
negative = -19
print(type(negative))
dictionary = {'name':'King', 'age': 36}
print(type(dictionary))
list = [1, 2, 3]
print(type(list))
tuple = (19, 21, 46)
print(type(tuple))
output
<class 'str'>
<class 'int'>
<class 'float'>
<class 'int'>
<class 'dict'>
<class 'list'>
<class 'tuple'>
isinstance()
 Python isinstance() function is used to check if an object is an instance of the
specified class or not.
syntax
isinstance(object, classinfo)
 This function returns True if the object is instance of classinfo argument or
instance of classinfo subclass.
 If the object is not an instance of classinfo or its subclass, then the function
returns False.
 classinfo argument can be a tuple of types. In that case, isinstance() will
return True if the object is an instance of any of the types.
 If classinfo is not a type or tuple of types, a TypeError exception is raised.
Example
i = 10
print('i is int:', isinstance(i, int))
f = 10.5
print('f is float:', isinstance(f, float))
s = 'a'
print('s is str:', isinstance(s, str))
t = (1, 2)
print('t is tuple:', isinstance(t, tuple))
li = []
print('li is list:', isinstance(li, list))
d = {}
print('d is dict:', isinstance(d, dict))
output
i is int: True
f is float: True
s is str: True
t is tuple: True
li is list: True
d is dict: True
Formatted String
 Python uses C-style string formatting to create new, formatted strings.
 The "%" operator is used to format a set of variables enclosed in a
"tuple" (a fixed size list), together with a format string, which contains
normal text together with "argument specifiers", special symbols like
"%i","%f","%s" and "%d".
 %i → int
%d → int
%f → float
%s → String type
Syntax
print("formatted string" %(variable list))
Example
a = 10
b = 20
c = 30
print("a value is %i" %a)
print("b value is %d and c value is %d" %(b,c))

Output
a value is 10
b value is 20 and c value is 30

Example
s = “Durga”
list = [10,20,30,40]
print("Hello %s ...The List of Items are %s" %(s,list))

Output
Hello Durga ...The List of Items are [10, 20, 30, 40]

format()
 This method lets us concatenate elements within a string through positional
formatting.
 The format() method formats the specified value(s) and insert them inside
the string's placeholder.
 The placeholder is defined using curly brackets: {}. The placeholders can be
identified using named indexes {price}, numbered indexes {0}, or even
empty placeholders {}.
 The format() method returns the formatted string. print() with replacement
operator {}
Syntax
string.format(value1, value2...)
Example
#named indexes:
txt = "My name is {Name}, I'm {age}".format(Name = "John", age = 36)
#numbered indexes:
txt2 = "My name is {0}, I'm {1}".format("John",36)
#empty placeholders:
txt3 = "My name is {}, I'm {}".format("John",36)
print(txt)
print(txt2)
print(txt3)
Output
My name is John, I’m 36
My name is John, I’m 36
My name is John, I’m 36

You might also like