0% found this document useful (0 votes)
4 views55 pages

Pyhton Unit1

Uploaded by

rajputdhruv385
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)
4 views55 pages

Pyhton Unit1

Uploaded by

rajputdhruv385
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/ 55

UNIT-1

Python Introduction
Python is developed by Guido van Rossum. Guido van Rossum started implementing Python in
1989. Python is a very simple programming language so even if you are new to programming,
you can learn python without facing any issues.

What can Python do?

• Python can be used on a server to create web applications.


• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.
• Python can be used for rapid prototyping, or for production-ready software
development.

Why Python?

• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a functional way.

Features of Python programming language


Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural programming
approaches and provides dynamic memory allocation. We have listed below a few essential
features.

1) Easy to Learn and Use

Python is easy to learn as compared to other programming languages. Its syntax is


straightforward and much the same as the English language. There is no use of the semicolon or
curly-bracket, the indentation defines the code block. It is the recommended programming
language for beginners.
2) Expressive Language

Python can perform complex tasks using a few lines of code. A simple example, the hello world
program you simply type print("Hello World"). It will take only one line to execute, while Java
or C takes multiple lines.

3) Interpreted Language

Python is an interpreted language; it means the Python program is executed one line at a time.
The advantage of being interpreted language, it makes debugging easy and portable.

4) 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. It enables programmers to develop the
software for several competing platforms by writing a program only once.

5) Free and Open Source

Python is freely available for everyone. It is freely available on its official website
www.python.org

. It has a large community across the world that is dedicatedly working towards make new
python modules and functions. Anyone can contribute to the Python community. The
opensource means, "Anyone can download its source code without paying any penny."

6) Object-Oriented Language

Python supports object-oriented language and concepts of classes and objects come into
existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented
procedure helps to programmer to write reusable code and develop applications in less code.

7) 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. It converts the program into byte code, and any platform can
use that byte code.
8) Large Standard Library

It provides a vast range of libraries for the various fields such as machine learning, web
developer, and also for the scripting. There are various machine learning libraries, such as
Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular
framework for Python web development.
9) GUI Programming Support

Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy are
the libraries which are used for developing the web application.

10) Integrated

It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by
line like C,C++ Java. It makes easy to debug the code.

11. Embeddable

The code of the other programming language can use in the Python source code. We can use
Python source code in another programming language as well. It can embed other language
into our code.

Python History and Versions

o Python laid its foundation in the late 1980s.

o The implementation of Python was started in December 1989 by Guido Van Rossum at
CWI in Netherland. o In February 1991, Guido Van Rossum published the code (labeled
version 0.9.0) o In 1994, Python 1.0 was released with new features like lambda, map,
filter, and reduce. o Python 2.0 added new features such as list comprehensions,
garbage collection systems. o On December 3, 2008, Python 3.0 (also called "Py3K") was
released. It was designed to rectify the fundamental flaw of the language.

o ABC programming language is said to be the predecessor of Python language, which


was capable of Exception Handling and interfacing with the Amoeba Operating System.

o The following programming languages influence Python:

o ABC language. o Modula-3


Python Version List

Python programming language is being updated regularly with new features and supports. There
are lots of update in Python versions, started from 1994 to current release.

A list of Python versions with its released date is given below.


Python Version Released Date

Python 1.0 January 1994

Python 1.5 December 31, 1997

Python 1.6 September 5, 2000

Python 2.0 October 16, 2000

Python 2.1 April 17, 2001

Python 2.2 December 21, 2001

Python 2.3 July 29, 2003

Python 2.4 November 30, 2004

Python 2.5 September 19, 2006

Python 2.6 October 1, 2008


Python 2.7 July 3, 2010

Python 3.0 December 3, 2008

Python 3.1 June 27, 2009

Python 3.2 February 20, 2011

Python 3.3 September 29, 2012

Python 3.4 March 16, 2014

Python 3.5 September 13, 2015

Python 3.6 December 23, 2016

Python 3.7 June 27, 2018

Python 3.8 October 14, 2019

Python Applications

Python is known for its general-purpose nature that makes it applicable in almost every domain
of software development. Python makes its presence in every emerging field. It is the
fastestgrowing programming language and can develop any application.

Here, we are specifying application areas where Python can be applied.


1) Web Applications

We can use Python to develop web applications. It provides libraries to handle internet protocols
such as HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser, etc. One of
Python web-framework named Django is used on Instagram. Python provides many useful
frameworks, and these are given below:

o Django and Pyramid framework(Use for heavy applications) o


Flask and Bottle (Micro-framework)

o Plone and Django CMS (Advance Content management)

2) Desktop GUI Applications

The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
application. Python provides a Tkinter or Tk GUI library to develop a user interface.

3) Console-based Application

Console-based applications run from the command-line or shell. These applications are computer
program which are used commands to execute. This kind of application was more popular in the
old generation of computers. Python can develop this kind of application very effectively.
4) Software Development

Python is useful for the software development process. It works as a support language and can
be used to build control and management, testing, etc.

5) Scientific and Numeric

This is the era of Artificial intelligence where the machine can perform the task the same as the
human. Python language is the most suitable language for Artificial intelligence or machine
learning. It consists of many scientific and mathematical libraries, which makes easy to solve
complex calculations.

6) Business Applications

Business Applications differ from standard applications. E-commerce and ERP are an example of
a business application. This kind of application requires extensively, scalability and readability,
and Python provides all these features.

Oddo is an example of the all-in-one Python-based application which offers a range of business
applications.
7) Audio or Video-based Applications

Python is flexible to perform multiple tasks and can be used to create multimedia applications.
Some multimedia applications which are made by using Python are TimPlayer, cplay, etc.

8) 3D CAD Applications

The CAD (Computer-aided design) is used to design engineering related architecture. It is used to
develop the 3D representation of a part of a system.

9) Enterprise Applications

Python can be used to create applications that can be used within an Enterprise or an
Organization.

10) Image Processing Application

Python contains many libraries that are used to work with the image. The image can be
manipulated according to our requirements.
Python Virtual Machine

Python Virtual Machine (PVM) is a program which provides programming environment. The role of PVM
is to convert the byte code instructions into machine code so the computer can execute those machine
code instructions and display the output.
Interpreter converts the byte code into machine code and sends that machine code to the computer
processor for execution.

Writing First Python Program


Python Syntax
Python syntax can be executed by writing directly in the Command Line:

>>> print("Hello, World!")


Hello, World!
Or by creating a python file on the server, using the .py file extension, and running it in the
Command Line:

C:\Users\Your Name>python myfile.py


Python Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code. Creating

a Comment

Comments starts with a #, and Python will ignore them:

Example
#This is a comment print("Hello,
World!")

Example print("Hello, World!") #This is a

comment

Comments spanning multiple lines have " " " or ' ' ' on either end. This is the same as a multiline
string, but they can be used as comments:
"""
This type of comment spans multiple lines.
These are mostly used for documentation of functions, classes and modules.
"""

Logical and Physical Lines


A physical line is what you see when you write the program. A logical line is what Python sees as
a single statement. Python implicitly assumes that each physical line corresponds to a logical
line.
An example of a logical line is a statement like print 'Hello World' - if this was on a line by itself
(as you see it in an editor), then this also corresponds to a physical line.

Implicitly, Python encourages the use of a single statement per line which makes code more
readable.
If you want to specify more than one logical line on a single physical line, then you have to
explicitly specify this using a semicolon (;) which indicates the end of a logical line/statement.
For example,
i = 5 print
i
is effectively same as
i = 5; print i; or even
i = 5; print i

However, I strongly recommend that you stick to writing a single logical line in a single
physical line only. Use more than one physical line for a single logical line only if the logical line
is really long.

Indentation
Whitespace is important in Python. Actually, whitespace at the beginning of the line is
important. This is called indentation. Leading whitespace (spaces and tabs) at the beginning of
the logical line is used to determine the indentation level of the logical line, which in turn is
used to determine the grouping of statements.
This means that statements which go together must have the same indentation. Each such set
of statements is called a block.
One thing you should remember is how wrong indentation can give rise to errors. For
example:
i=5
print 'Value is', i # Error! Notice a single space at the start of the line print
'I repeat, the value is', i
When you run this, you get the following error:
File "whitespace.py", line 4
print 'Value is', i # Error! Notice a single space at the start of the line
^
SyntaxError: invalid syntax
Notice that there is a single space at the beginning of the second line. The error indicated by
Python tells us that the syntax of the program is invalid i.e. the program was not properly
written. What this means to you is that you cannot arbitrarily start new blocks of statements
(except for the main block which you have been using all along, of course).

How to indent
Do not use a mixture of tabs and spaces for the indentation as it does not work across different
platforms properly. I strongly recommend that you use a single tab or two or four spaces for
each indentation level.
Python Variables

Variables are containers for storing data values.

Declaring Variable and Assigning Values

Python does not bind us to declare a variable before using it in the application. It allows us to
create a variable at the required time.

We don't need to declare explicitly variable in Python. When we assign any value to the variable,
that variable is declared automatically.

The equal (=) operator is used to assign value to a variable. A


variable is created the moment you first assign a value to it.

Example
x=5
y = "John"
print(x) print(y)

Variable (Identifier) Naming

Rules for Naming Python variables:


• A variable name must start with a letter or the underscore character (_)
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)

• Variable name must not contain any white-space


• Variable name must not be similar to any keyword defined in the language.

• Examples of valid variable: a123, _n, n_9, etc.


• Examples of invalid variable: 1a, n%4, n 9, etc.

Python Variables - Assign Multiple Values


Python allows you to assign values to multiple variables in one line:

Example

x, y, z = "Orange", "Banana", "Cherry"


print(x) print(y) print(z)

Determine the type of variable ( Get the Type Of Variable)

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.

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

Example 1
x=5
y = "John"
print(type(x))
print(type(y)) output

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

Example 2

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

Output:
<type 'int'> <type
'str'>
<type 'float'>

Python Operators
Operators are used to perform operations on variables and values. Python
divides the operators in the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical
operations:

Operator Name Example


+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y floor(x/y)

Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As


= x=5 x=5
+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3
Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example


== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Python Logical Operators
Logical operators are used to combine conditional statements:

Operator Description Example


and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is not(x < 5 and x < 10)
true

Example
x=5
print(x > 3 and x < 10)
# returns True because 5 is greater than 3 AND 5 is less than 10 Python

Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location:

Operator Description Example


is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y
Example

x = ["apple", "banana"] y
= ["apple", "banana"]
z=x

print(x is z)

# returns True because z is the same object as x

print(x is y)

# returns False because x is not the same object as y, even if they have the same content

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example


in Returns True if a sequence with the specified value is present in the x in y
object
not in Returns True if a sequence with the specified value is not present in the x not in y
object
Example

x = ["apple", "banana"]
print("banana" in x)

# returns True because a sequence with the value "banana" is in the list Python

Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description


& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< left shift Shift left by pushing zeros in from the right
>> right shift Shift right by pushing zeros in from the left and let the rightmost
bits fall off

Data Types in Python


Built-in Data Types

In programming, data type is an important concept.


Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

String (Text) Type: str


Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict


Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview


Setting the Data Type

In Python, the data type is set when you assign a value to a variable:

Example Data Type

x = "Hello World" str

x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", "cherry"}) frozenset


x = True bool

x = b"Hello" bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview
Setting the Specific Data Type

If you want to specify the data type, you can use the following constructor functions:

Example Data Type

x = str("Hello World") str

x = int(20) int

x = float(20.5) float

x = complex(1j) complex

x = list(("apple", "banana", "cherry")) list

x = tuple(("apple", "banana", "cherry")) tuple

x = range(6) range

x = dict(name="John", age=36) dict


x = set(("apple", "banana", "cherry")) set

x = frozenset(("apple", "banana", "cherry")) frozenset

x = bool(5) bool

x = bytes(5) bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

Numeric Types
Python supports three types of numeric data.

1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer. Its value belongs to int

2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.

3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.

Variables of numeric types are created when you assign a value to them:

Complex numbers are written with a "j" as the imaginary part:

Example
x = 1 # int
y = 2.8 # float z =
4+1j # complex
To verify the type of any object in Python, use the type() function:
Python Casting (Explicit conversion of data type)

Specify a Variable Type

There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data
types, including its primitive types.

Casting in python is therefore done using constructor functions:

• int() - constructs an integer number from an integer literal, a float literal (by removing
all decimals), or a string literal (providing the string represents a whole number)
• float() - constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals

Example-1

x =
int(1) y =
int(2.8) z =
int("3")
print(x)
print(y)
print(z)

output
1
2
3

Example-
2
x =
float(1)
y =
float(2.8) z
=
float("3")
w=
float("4.2"
) print(x)
print(y)
print(z)
print(w)
output
1.0
2.8
3.0
4.2

Example-3

x = str("s1")
y = str(2) z
= str(3.0)
print(x)
print(y)
print(z)

output
s1 2
3.0

String
The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.

In the case of string handling, the operator + is used to concatenate two strings as the operation
"hello"+" python" returns "hello python".
The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python
Python'.

The following example illustrates the string in Python. Example

-1

str = "string using double quotes"


print(str) s = '''''A multiline
string''' print(s)
Output:

string using double quotes


A multiline string

Slicing Strings

Slicing

You can return a range of characters by using the slice syntax.


Specify the start index and the end index, separated by a colon, to return a part of the string.

Example

Get the characters from position 2 to position 5 (not included):


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

output

llo

Note: The first character has index 0.

Slice From the Start


By leaving out the start index, the range will start at the first character:
Example

Get the characters from the start to position 5 (not included):

b = "Hello, World!"

print(b[:5]) output
Hello

Slice To the End


By leaving out the end index, the range will go to the end:

Example

Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])

output llo,

World!

Example - 2

str1 = 'hello javatpoint' #string str1 str2 = ' how are you' #string
str2 print (str1[0:2]) #printing first two character using slice
operator print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice

print (str1 + str2) #printing the concatenation of str1 and str2

Output:

he o hello javatpointhello
javatpoint hello javatpoint how
are you
List
Python Lists are similar to arrays in C. However, the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].

We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the strings.

• List is a collection which is ordered and changeable. Allows duplicate members.


• The list is changeable, meaning that we can change, add, and remove items in a list
after it has been created.

Consider the following example.

list1 = [1, "hi", "Python", 2]


#Checking type of given list
print(type(list1))

#Printing the list1 print


(list1)

# List slicing print


(list1[3:])

# List slicing print


(list1[0:2])

# List Concatenation using + operator print


(list1 + list1)

# List repetation using * operator print


(list1 * 3)
Output:

[1, 'hi', 'Python', 2]


[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
Change Item Value
To change the value of a specific item, refer to the index number:
Example

Change the second item:


thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant" print(thislist)

Add (Append) Items


To add an item to the end of the list, use the append() method:

Example

Using the append() method to append an item:


thislist = ["apple", "banana", "cherry"]
thislist.append("orange") print(thislist)

Insert Items
To insert a list item at a specified index, use the insert() method.

The insert() method inserts an item at the specified index:

Example

Insert an item as the second position:


thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange") print(thislist)

Remove Specified Item


The remove() method removes the specified item.

Example

Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana") print(thislist)

Remove Specified Index


The pop() method removes the specified index.

Example

Remove the second item:

thislist = ["apple", "banana", "cherry"]


thislist.pop(1) print(thislist)

Sort List Alphanumerically

List objects have a sort() method that will sort the list alphanumerically, ascending, by default:

Example

Sort the list alphabetically:


thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort() print(thislist)

Sort Descending

To sort descending, use the keyword argument reverse = True:

Example

Sort the list descending:


thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True) print(thislist)

Join Two Lists

There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.

Example

Join two list:


list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1 + list2 print(list3)

Loop Through a List

You can loop through the list items by using a for loop:

Example

Print all items in the list, one by one:

thislist = ["apple", "banana", "cherry"]


for x in thislist: print(x)

Loop Through the Index Numbers

You can also loop through the list items by referring to their index number.

Use the range() and len() functions to create a suitable iterable.

Example

Print all items by referring to their index number:

thislist = ["apple", "banana", "cherry"] for


i in range(len(thislist)): print(thislist[i])

Note: The iterable created in the example above is [0, 1, 2].

Using a While Loop

You can loop through the list items by using a while loop.
Use the len() function to determine the length of the list, then start at 0 and loop your way
through the list items by referring to their indexes. Remember to increase the index by 1
after each iteration.

Example

Print all items, using a while loop to go through all the index numbers
thislist = ["apple", "banana", "cherry"]
i = 0 while i <
len(thislist):
print(thislist[i])
i=i+1

List Comprehension

List comprehension offers a shorter syntax when you want to create a new list based on the
values of an existing list.

Example:

Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the
name.

Without list comprehension you will have to write a for statement with a conditional test
inside:

Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
if "a" in x:
newlist.append(x)

print(newlist) output

[‘apple’,’banana’,’mango’]
With list comprehension you can do all that with only one line of code:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)

output

[‘apple’,’banana’,’mango’]

The Syntax

newlist = [expression for item in iterable if condition == True]

The return value is a new list, leaving the old list unchanged.

Condition

The condition is like a filter that only accepts the items that valuate to True.

Example

Only accept items that are not "apple":


newlist = [x for x in fruits if x != "apple"]

Looping Using List Comprehension

List Comprehension offers the shortest syntax for looping through lists:

Example

A short hand for loop that will print all items in a list:
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]

output

apple banana
cherry

Tuple

A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and
enclosed in parentheses ().

A tuple is a read-only data structure as we can't modify the size and value of the items of a
tuple.

Access Tuple Items

You can access tuple items by referring to the index number, inside square brackets:

Example

Print the second item in the tuple:

thistuple = ("apple", "banana", "cherry") print(thistuple[1])

Negative Indexing

Negative indexing means start from the end.

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

Example

Print the last item of the tuple:


thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.

When specifying a range, the return value will be a new tuple with the specified items.

Example

Return the third, fourth, and fifth item:


thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])

Update Tuples

Change Tuple Values

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or
immutable as it also is called.

But there is a workaround. You can convert the tuple into a list, change the list, and convert the
list back into a tuple.

Example

Convert the tuple into a list to be able to change it:


x = ("apple", "banana", "cherry")
y = list(x) y[1]
= "kiwi" x =
tuple(y)

print(x)

Add Items

Since tuples are immutable, they do not have a build-in append() method, but there are other
ways to add items to a tuple.

1. Convert into a list: Just like the workaround for changing a tuple, you can convert it into a
list, add your item(s), and convert it back into a tuple.
Example

Convert the tuple into a list, add "orange", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange") thistuple =
tuple(y)

2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one item, (or
many), create a new tuple with the item(s), and add it to the existing tuple:

Example

Create a new tuple with the value "orange", and add that tuple:
thistuple = ("apple", "banana", "cherry")
y = ("orange",) thistuple +=
y

print(thistuple)

Remove Items

Note: You cannot remove items in a tuple.


Tuples are unchangeable, so you cannot remove items from it, but you can use the same
workaround as we used for changing and adding tuple items:

Example

Convert the tuple into a list, remove "apple", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple") thistuple =
tuple(y)

Example

The del keyword can delete the tuple completely:


thistuple = ("apple", "banana", "cherry") del
thistuple
print(thistuple) #this will raise an error because the tuple no longer exists

Join Two Tuples

To join two or more tuples you can use the + operator:

Example

Join two tuples:

tuple1 = ("a", "b" , "c") tuple2 =


(1, 2, 3)

tuple3 = tuple1 + tuple2 print(tuple3)

Example

Let's see a simple example of the tuple.

tup = ("hi", "Python", 2) #


Checking type of tup print
(type(tup))

#Printing the tuple print


(tup)

# Tuple slicing print


(tup[1:]) print
(tup[0:1])

# Tuple concatenation using + operator print


(tup + tup)
# Tuple repatation using * operator
print (tup * 3)

# Adding value to tup. It will throw an error. t[2] =


"hi"

Output:

<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (most recent call last):


File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

Loop Through a Tuple

You can loop through the tuple items by using a for loop.

Example

Iterate through the items and print the values:


thistuple = ("apple", "banana", "cherry")
for x in thistuple: print(x)

output

apple
banana
cherry
Range
The range() function returns a sequence of numbers, starting from 0 by default, and increments by
1 (by default), and stops before a specified number.
Syntax range(start, stop,
step) Parameter Values

Parameter Description

start Optional. An integer number specifying at which position to start. Default is 0

Required. An integer number specifying at which position to stop (not


stop
included).

step Optional. An integer number specifying the incrementation. Default is 1

Example

Create a sequence of numbers from 3 to 5, and print each item in the sequence:
x = range(3, 6)
for n in x: print(n)
output

3
4
5
Example

Create a sequence of numbers from 3 to 19, but increment by 2 instead of 1:

x = range(3, 20, 2) for


n in x: print(n)
Mapping Types

Dictionary
Dictionary is an unordered set (in python 3.6 and earlier version) of a key-value pair of items. It is
like an associative array or a hash table where each key stores a specific value. Key can hold any
primitive data type, whereas value is an arbitrary Python object.

The items in the dictionary are separated with the comma (,) and enclosed in the curly braces
{}.

Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

Consider the following example.

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}

# Printing dictionary print


(d)

# Accesing value using keys print("1st


name is "+d[1]) print("2nd name is "+
d[4])

print (d.keys()) print


(d.values())

Output:

1st name is Jimmy


2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'} dict_keys([1,
2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
if we want to display key and values from dictionary then add following code in above example.

Example:

for key , value in d.items():

print(key,' - ',value)

output

1 - 45

2 - Alex

3 - john 4 - mike

Boolean

Boolean type provides two built-in values, True and False. These values are used to determine the
given statement true or false. It denotes by the class bool. True can be represented by any non-zero
value or 'T' whereas false can be represented by the 0 or 'F'. Consider the following example.

# Python program to check the boolean type


print(type(True)) print(type(False)) print(false)
Output:

<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

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

A set is a collection which is unordered, unchangeable and unindexed.

Note: Set items are unchangeable, but you can remove items and add new items.
Note: Sets are unordered, so you cannot be sure in which order the items will appear.

Duplicates Not Allowed

Sets cannot have two items with the same value.

The set is created by using a built-in function set(), or a sequence of elements is passed in the curly
braces and separated by the comma. It can contain various types of values. Consider the following
example.

# Creating Empty set


set1 = set()

set2 = {'James', 2, 3,'Python'}

#Printing Set value


print(set2)

# Adding element to the set

set2.add(10)
print(set2)

#Removing element from the set


set2.remove(2) print(set2)

Output:

{3, 'Python', 'James', 2}


{'Python', 'James', 3, 2, 10} {'Python',
'James', 3, 10}

Add Items
Once a set is created, you cannot change its items, but you can add new items. To
add one item to a set use the add() method.

Example
Add an item to a set, using the add() method:

thisset = {"apple", "banana", "cherry"}


thisset.add("orange") print(thisset)

output
{'apple', 'banana', 'orange', 'cherry'} Remove
Item
To remove an item in a set, use the remove()

Example
Remove "banana" by using the remove() method:

thisset = {"apple", "banana", "cherry"}


thisset.remove("banana")
print(thisset)

output
{'cherry', 'apple'}

FrozenSets

The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen set cannot
be changed and therefore it can be used as a key in the dictionary.

The elements of the frozen set cannot be changed after the creation. We cannot change or append
the content of the frozen sets by using the methods like add() or remove().

The frozenset() method is used to create the frozenset object. The iterable sequence is passed into
this method which is converted into the frozen set as a return type of the method.
Consider the following example to create the frozen set. Frozenset =

frozenset([1,2,3,4,5])
print(type(Frozenset)) print("\nprinting the
content of frozen set...") for i in Frozenset:
print(i);

Frozenset.add(6) #gives an error since we cannot change the content of Frozenset after creatio n

Output:

<class 'frozenset'>

printing the content of frozen set...


1
2
3
4
5
Traceback (most recent call last):
File "set.py", line 6, in <module>
Frozenset.add(6) #gives an error since we can change the content of Frozenset after creation
AttributeError: 'frozenset' object has no attribute 'add'

Binary Types:

bytes, bytearray, memoryview

bytes and bytearray are used for manipulating binary data. The memoryview uses the buffer
protocol to access the memory of other binary objects without needing to make a copy.

Bytes objects are unchallengeable sequences of single bytes. We should use them only when
working with ASCII compatible data.

The syntax for bytes literals is same as string literals, except that a 'b' prefix is added.

bytearray objects are always created by calling the constructor bytearray(). These are mutable
(changeable) objects.
Example

hexStr = bytes.fromhex('A2f7 4509')


print(hexStr) byteString =
b'\xa2\xf7E\t'
print(byteString.hex())

bArray1 = b"XYZ"
bArray2 = bArray1.replace(b"X", b"P") print(bArray2)

byteArray1 = b'ABBABCACBBACA'
print(byteArray1.count(b'AC'))

print(byteArray1.find(b'CA')) # return position of first occurrence of ‘CA’

myByteArray = bytearray('String', 'UTF-8') #unicode Transformation format 8


memView = memoryview(myByteArray)

print(memView[0]) #ASCII of 'S' print(bytes(memView[1:5]))

OUTPUT

b'\xa2\xf7E\t'
a2f74509 b'PYZ'
2
5 83
b'trin'
Control Statements

Conditional Statements
Type of condition statement in Python:

• If statement.
• If Else statement.
• Elif statement.
• Nested if statement.
• Nested if else statement.
• Elif Ladder

If statement

If statement is most usually used as a conditional statement.

Syntax
If ( condition ):
Block of code

The if condition evaluates a Boolean expression and executes the block of code only when the
Boolean expression becomes TRUE.
Example

Program for if statement,


a = 10 b =
20 if a<b:
print("a is less than b")

output

a is less than b

If else statement
If else is a conditional statement. The statement itself says that if a given condition is true or false.
True means executing the “if” statement to the output. False means executing the “else”
statement to the output.

Syntax
if(condition): #
if statement else:
# else statement

Here, the condition will be evaluated to a Boolean expression (true or false). If the condition is true
then the statements or program present inside the “if” block will be executed and if the condition
is false then the statements or program present inside the “else” block will be executed.
Example 1

Program for if else statement,


a = 10 b =
20 if a==b:
print("a and b are equal") else:
print("a and b are not equal")

output

a and b are not equal

Example 47
= 48

print(“number is less than 10”)

print (“This statement will always be executed” )

Output

number is less than 10


This statement will always be executed
Elif statement

Elif is a shortcut of else if condition statements. In Python one or more conditions are used in the
elif statement.

Syntax if
(condition):
#Set of statement to execute if condition is true elif
(condition):
#Set of statements to be executed when if condition is false and elif condition is true else:
#Set of statement to be executed when both if and elif conditions are false

Program for elif statement


Example
a = 10 b = 10 if a > b:
print("a is greater than b")
elif a == b:
print("a and b are equal") else:
print("b is greater than a")

output

a and b are equal

Nested if statement

Nested “if-else” statements mean that an “if” statement or “if-else” statement is present inside
another if or if-else block. Python provides this feature as well, this in turn will help us to check
multiple conditions in a given program.

An “if” statement is present inside another “if” statement which is present inside another “if”
statements and so on.

Nested if Syntax: if(condition):


#Statements to execute if condition is true
if(condition):
#Statements to execute if condition is true
#end of nested if
#end of if
The above syntax clearly says that the if block will contain another if block in it and so on. If block
can contain ‘n’ number of if block inside it.

Example

Program for nested if statement,


a= 1001 if a> 100:
print("Above 100")
if a > 1000:
print("and also above 1000")

output Above 100


and also above 1000

Nested if else statement

Nested if-else Syntax: if(condition):


#Statements to execute if condition is true
if(condition):
#Statements to execute if condition is true
else:
#Statements to execute if condition is false else:
#Statements to execute if condition is false
Here we have included the “if-else” block inside an if block, you can also include an “if-else” block
inside “else” block.

Example: 1 num = -7 if (num != 0):


if (num > 0): print(“Number
is positive”) else:
print(“Number is negative”)
else: print(“Number is Zero”)

Output:
Number is negative

Example 2
Program for nested if else statement,
a=int(input("enter the a value"))#user give a value if
a> 100:
print("Above 100")
if a > 1000:
print("and also above 1000")
else: print("and also below
1000") else:
print("below 100")

output

enter the a value1001


Above 100 and also
above 1000

Elif Ladder

As the name itself suggests a program that contains a ladder of “elif” statements or “elif”
statements are structured in the form of a ladder.

This statement is used to test multiple expressions.

Syntax:
if (condition):
#Set of statement to execute if condition is true elif
(condition):
#Set of statements to be executed when if condition is false and elif condition is true elif
(condition):
#Set of statements to be executed when both if and first elif condition is false and
#second elif condition is true elif
(condition):
#Set of statements to be executed when if, first elif and second elif conditions are false and
#third elif statement is true else:
#Set of statement to be executed when all if and elif conditions are false
PYTHON PROGRAMMING

Example: 1
my_marks = 90 if
(my_marks < 35):
print(“Sorry!, You failed the exam”)
elif(my_marks > 60 and my_marks > 100):
print(“Passed in First class”) else:
print(“Passed in First class with distinction”)
Output:
Passed in First class with distinction

Short Hand If
If you have only one statement to execute, you can put it on the same line as the if
statement.
Example
One line if statement
if a > b: print("a is greater than b")

Short Hand If ... Else


If you have only one statement to execute, one for if, and one for else, you can put it all on
the same line:

Example
One line if else statement:

a=2
b=
330
print("A") if a > b else print("B")

output
A

You can also have multiple else statements on the same line:

Example
One line if else statement, with 3 conditions:

a = 330
b=
330
print("A") if a > b else print("=") if a == b else print("B")
PYTHON PROGRAMMING

output
=

The pass Statement if statements cannot be empty, but if you for some reason have
an if statement with no content, put in the pass statement to avoid getting an error.

Examp
le a =
33 b =
200 if
b > a:
pass

Looping statements
While Loop:
In python, while loop is used to execute a block of statements repeatedly until a given a
condition is satisfied. And when the condition becomes false, the line immediately after
the loop in program is executed.

Syntax :

while condition:
statement(s)

All the statements indented by the same number of character spaces after a
programming construct are considered to be Part of a single block of code. Python uses
indentation as its method of grouping statements.

# Python program to illustrate


# while loop count =
0 while (count < 3):
count = count + 1
print("Hello World")

Using else statement with while loops

With the else statement we can run a block of code once when the condition no longer is
true:

syntax

while condition:
PYTHON PROGRAMMING

# execute these statements


else:
# execute these statements

Example
count = 0
while count < 3:
count = count + 1
print("Hello World") else:
print('end')
• Single statement while block: Just like the if block, if the while block consists of a single
statement the we can declare the entire loop in a single line as shown below:
# Python program to illustrate
# Single statement while block
count = 0
while (count == 0): print("Hello Geek")
• Note: It is suggested not to use this type of loops as it is a never ending infinite loop
where the condition is always true and you have to forcefully terminate the compiler.

The break Statement


With the break statement we can stop the loop even if the while condition is true:

Example

Exit the loop when i is 3:


i=1
while i <
6:
print(i)
if i == 3:
break i
+= 1

The continue Statement


With the continue statement we can stop the current iteration, and continue with the next:

Example

Continue to the next iteration if i is 3:


i=0
while i < 6:
PYTHON PROGRAMMING

i += 1
if i ==3:
continue
print(i)

for in Loop:
For loops are used for sequential traversal. (that is either a list, a tuple, a range, a dictionary, a set, or
a string).
For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for
(i=0; i<n; i++). There is “for in” loop which is similar to for each loop in other languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set
etc.
Syntax:
for iterator_var in sequence:
statements(s)

Example 1
# Python program to illustrate
# Iterating over range 0 to n-1

n = 4 for i in
range(0, n):
print(i)
Output :
0
1
2
3

Example 2
Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

output

apple
banana
cherry
PYTHON PROGRAMMING

Looping Through a String


Even strings are iterable objects, they contain a sequence of characters:

Example

Loop through the letters in the word "banana":

for x in "banana":

print(x)

output

The break Statement


With the break statement we can stop the loop before it has looped through all the items:

Example

Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x) if x
== "banana":
break
PYTHON PROGRAMMING

The continue Statement


With the continue statement we can stop the current iteration of the loop, and continue
with the next:

Example

Do not print banana:


fruits = ["apple", "banana",
"cherry"] for x in fruits: if x ==
"banana":
continue
print(x)

Else in For Loop


The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:

Example

Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x) else:
print("Finally
finished!") The pass
Statement

for loops cannot be empty, but if you for some reason have a for loop with no content, put
in the pass statement to avoid getting an error.

Example
for x in [0, 1, 2]:
pass

Example using list, tuple, string, dictionary

# Python program to illustrate


# Iterating over a list
print("List Iteration") l =
["geeks", "for", "geeks"]
for i in l: print(i)
PYTHON PROGRAMMING

# Iterating over a tuple


(immutable) print("\nTuple
Iteration") t = ("geeks", "for",
"geeks")
for i in t:
print(i)

# Iterating over a String


print("\nString Iteration")
s = "Geeks"
for i in s :
print(i)

# Iterating over dictionary


print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
print(i, d[i])

Output:
List Iteration
geeks
for
geeks

Tuple Iteration
geeks
for
geeks

String Iteration
G
e
e
k
s

Dictionary
Iteration xyz 123
abc 345
PYTHON PROGRAMMING

Nested Loops
A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":
Nested Loops: Python programming language allows to use one loop inside another loop.
Following section shows few examples to illustrate the concept.

Syntax:

for iterator_var in sequence:


for iterator_var in sequence:
statements(s)
statements(s)

The syntax for a nested while loop statement in Python programming language is as follows:

Syntax:

while expression:
while expression:
statement(s)
statement(s)

Example

Print each adjective for every fruit:

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in
fruits:
print(x, y)

output red
apple red
banana
red cherry
big apple
big
PYTHON PROGRAMMING

banana
big cherry
tasty
apple
tasty
banana
tasty
cherry
Example
# Python program to illustrate
# nested for loops in Python

for i in range(1, 5):


for j in range(i):
print(i, end=' ')
print()
Output:
1
22
333
4444

You might also like