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

PDF Advanced Programming Module

The document provides information about Python programming language including its history, features, uses cases, and how to install and set up the Python environment. It also describes the basic Python syntax and how to execute Python programs from the command line or within a file.

Uploaded by

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

PDF Advanced Programming Module

The document provides information about Python programming language including its history, features, uses cases, and how to install and set up the Python environment. It also describes the basic Python syntax and how to execute Python programs from the command line or within a file.

Uploaded by

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

ADVANCED PROGRAMMING

MODULE-1
TEACHING SCHEME: 3-1-0 (L-T-P) CREDIT:3

1. Introduction:

What is Python

Python is a general purpose, dynamic, high-level, and interpreted programming


language. It supports Object Oriented programming approach to develop
applications. It is simple and easy to learn and provides lots of high-level data
structures.

 Python is easy to learn yet powerful and versatile scripting language, which
makes it attractive for Application Development.
 Python's syntax and dynamic typing with its interpreted nature make it an
ideal language for scripting and rapid application development.
 Python supports multiple programming pattern, including object-oriented,
imperative, and functional or procedural programming styles.
 Python is not intended to work in a particular area, such as web
programming. That is why it is known as multipurpose programming
language because it can be used with web, enterprise, 3D CAD, etc.
 We don't need to use data types to declare variable because it is dynamically
typed so we can write a=10 to assign an integer value in an integer variable.
 Python makes the development and debugging fast because there is no
compilation step included in Python development, and edit-test-debug cycle
is very fast.

Python 2 vs. Python 3

A list of differences between Python 2 and Python 3 are given below:

1. Python 2 uses print as a statement and used as print "something" to print


some string on the console. On the other hand, Python 3 uses print as a
function and used as print("something") to print something on the console.
2. Python 2 uses the function raw_input () to accept the user's input. It returns
the string representing the value, which is typed by the user. To convert it
into the integer, we need to use the int() function in Python. On the other
hand, Python 3 uses input() function which automatically interpreted the
type of input entered by the user. However, we can cast this value to any
type by using primitive functions (int(), str(), etc.).
3. In Python 2, the implicit string type is ASCII, whereas, in Python 3, the implicit
string type is Unicode.
4. Python 3 doesn't contain the xrange() function of Python 2. The xrange() is
the variant of range() function which returns a xrange object that works
similar to Java iterator. The range() returns a list for example the function
range(0,3) contains 0, 1, 2.
5. There is also a small change made in Exception handling in Python 3. It
defines a keyword as which is necessary to be used. We will discuss it in
Exception handling section of Python programming tutorial.

Python History

Python was invented by Guido Van Rossum in 1991 at CWI in Netherland. The idea
of Python programming language has taken from the ABC programming language
or we can say that ABC is a predecessor of Python language.

There is also a fact behind the choosing name Python. Guido van Rossum was a fan
of the popular BBC comedy show of that time, "Monty Python's Flying Circus". So
he decided to pick the name Python for his newly created programming language.

Why learn Python?

 Python provides many useful features to the programmer. These features


make it most popular and widely used language. We have listed below few-
essential feature of Python.
 Easy to use and Learn
 Expressive Language
 Interpreted Language
 Object-Oriented Language
 Open Source Language
 Extensible
 Learn Standard Library
 GUI Programming Support
 Integrated
 Embeddable
 Dynamic Memory Allocation
 Wide Range of Libraries and Frameworks

Where is Python used?

Python is a general-purpose, popular programming language and it is used in


almost every technical field. The various areas of Python use are given below.

 Data Science
 Date Mining
 Desktop Applications
 Console-based Applications
 Mobile Applications
 Software Development
 Artificial Intelligence
 Web Applications
 Enterprise Applications
 3D CAD Applications
 Machine Learning
 Computer Vision or Image Processing Applications.
 Speech Recognitions
What can be done with Python?

How to Install Python (Environment Set-up)

In order to become Python developer, the first step is to learn how to install or
update Python on a local machine or computer. In this tutorial, we will discuss the
installation of Python on various operating systems.

Installation on Windows

Visit the link https://www.python.org/downloads/ to download the latest release


of Python. In this process, we will install Python 3.8.6 on our Windows operating
system. When we click on the above link, it will bring us the following page.
Step - 1: Select the Python's version to download.

Click on the download button

Step - 2: Click on the Install Now

Double-click the executable file, which is downloaded; the following window will
open. Select Customize installation and proceed. Click on the Add Path check box,
it will set the Python path automatically.
We can also click on the customize installation to choose desired location and
features. Other important thing is install launcher for the all user must be checked.

Step - 3 Installations in Process

Python Interpreter: Shell/REPL

 Python is an interpreter language. It means it executes the code line by line.


Python provides a Python Shell, which is used to execute a single Python
command and display the result.
 It is also known as REPL (Read, Evaluate, Print, and Loop), where it reads the
command, evaluates the command, prints the result, and loop it back to read
the command again.
 To run the Python Shell, open the command prompt or power shell on
Windows and terminal window, write python and press enter. A Python
Prompt comprising of three greater-than symbols >>> appears.

Executing Python Program from Command Line

First Python Program

In this Section, we will discuss the basic syntax of Python, we will run a simple
program to print Hello World on the console.

Python provides us the two ways to run a program:

 Using Interactive interpreter prompt


 Using a script file

Let's discuss each one of them in detail.

Interactive interpreter prompt

Python provides us the feature to execute the Python statement one by one at the
interactive prompt. It is preferable in the case where we are concerned about the
output of each line of our Python program.
To open the interactive mode, open the terminal (or command prompt) and type
python (python3 in case if you have Python2 and Python3 both installed on your
system).

It will open the following prompt where we can execute the Python statement and
check their impact on the console.

Using a script file (Script Mode Programming)

The interpreter prompt is best to run the single-line statements of the code.
However, we cannot write the code every-time on the terminal. It is not suitable to
write multiple lines of code.

Using the script mode, we can write multiple lines code into a file which can be
executed later. For this purpose, we need to open an editor like notepad, create a
file named and save it with .py extension, which stands for "Python". Now, we will
implement the above example using the script mode.

print ("hello world"); #here, we have used print() function to print the message
on the console.

To run this file named as first.py, we need to run the following command on the
terminal.

Step - 1: Open the Python interactive shell, and click "File" then choose "New", it
will open a new blank script in which we can write our code.

Step -2: Now, write the code and press "Ctrl+S" to save the file.
Step - 3: After saving the code, we can run it by clicking "Run" or "Run Module". It
will display the output to the shell.

The output will be shown as follows.


Step - 4: Apart from that, we can also run the file using the operating system
terminal. But, we should be aware of the path of the directory where we have
saved our file.

 Open the command line prompt and navigate to the directory.

 We need to type the python keyword, followed by the file name and hit
enter to run the Python file.

Summary:
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

Tools used for Implementing Python Code:

To See the Documentation in Python visit the following site

Access local Python documentation, if installed, or start a web browser and


open docs.python.org showing the latest Python documentation

Parts of Python Programming:

Keywords

Variables
What are Reserved Keywords in Python?
Reserved words (also called keywords) are defined with predefined meaning and
syntax in the language. These keywords have to be used to develop programming
instructions. Reserved words can’t be used as identifiers for other programming
elements like name of variable, function etc.
Following is the list of reserved keywords in Python 3
and except lambda with
as finally nonlocal while
assert false None yield
break for not
class from or
continue global pass
def if raise
del import return
elif in True
else is try
Python 3 has 33 keywords while Python 2 has 30. The print has been removed from
Python 2 as keyword and included as built-in function.
Hello, World!
Variables
Variables are containers for storing data values.

Creating Variables

Python has no command for declaring a variable.

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


Example:

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

o/p:

5
John

Casting
If you want to specify the data type of a variable, this can be done with casting.

Example

x = str(3) # x will be '3'


y = int(3) # y will be 3
z = float(3) # z will be 3.0

print(x)

print(y)

print(z)

o/p

3
3
3.0

Get the Type


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

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

o/p:

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

Single or Double Quotes?


String variables can be declared either by using single or double quotes:

Example

x = "John"

print(x)

#double quotes are the same as single quotes:

x = 'John'

print(x)

o/p:

John
John

Case-Sensitive
Variable names are case-sensitive.

Example
This will create two variables:

a=4
A = "Sally"

print(a)
print(A)

o/p:
4
Sally

Python - Variable Names


Naming Convention in Python
Python Variable Names
 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)
Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
print(myvar)
print(my_var)
print(_my_var)
print(myVar)
print(MYVAR)
print(myvar2)

o/p:

John
John
John
John
John
John

Many Values to Multiple Variables


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)

o/p:

Orange
Banana
Cherry

Output Variables
The Python print statement is often used to output variables.

To combine both text and a variable, Python uses the + character:

Example

x = "awesome"
print("Python is " + x)

o/p:

Python is awesome

Global Variables
Variables that are created outside of a function (as in all of the examples above) are known as
global variables.

Global variables can be used by everyone, both inside of functions and outside.

Example
Create a variable outside of a function, and use it inside the function
x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

o/p:

Python is awesome

If you create a variable with the same name inside a function, this variable will be local, and can
only be used inside the function. The global variable with the same name will remain as it was,
global and with the original value.
Example
Create a variable inside a function, with the same name as the global variable
x = "awesome"

def myfunc():
x = "fantastic"
print("Python is " + x)

myfunc()

print("Python is " + x)

o/p:

Python is fantastic
Python is awesome

The global Keyword


Normally, when you create a variable inside a function, that variable is local, and can only be used
inside that function.
To create a global variable inside a function, you can use the global keyword.
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)
o/p:
Python is fantastic

Python Operators
Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example
print(5 + 3)

o/p:

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:

Python Assignment Operators


Assignment operators are used to assign values to variables:

Python Comparison Operators


Comparison operators are used to compare two values:

Python Logical Operators


Logical operators are used to combine conditional statements:

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:

Python Membership Operators


Membership operators are used to test if a sequence is presented in an object:
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Operator Precedence and Associativity in Python
The following table shows the precedence of Python operators. The upper operator
holds higher precedence than the lower operator.

Operators Meaning

() Parentheses

** Exponent

+x, -x, ~x Unary plus, Unary minus, Bitwise NOT

*, /, //, % Multiplication, Division, Floor division, Modulus

+, - Addition, Subtraction

<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators

not Logical NOT

and Logical AND

or Logical OR
Example 1:
1. # Precedence of and and or operators
2. colour = "red"
3.
4. quantity = 0
5.
6. if colour == "red" or colour == "green" and quantity >= 5:
7. print("Your parcel is dispatched")
8. else:
9. print("your parcel cannot be dispatched")

O/p:
Your parcel is dispatched
Python Indentation
Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is for readability


only, the indentation in Python is very important.

Python uses indentation to indicate a block of code.

Example:

if 5 > 2:
print("Five is greater than two!")
o/p:

Five is greater than two!


Python will give you an error if you skip the indentation:
Example

Syntax Error:

if 5 > 2:
print("Five is greater than two!")
o/p

Syntax Error:

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!")
o/p:

Hello, World!
Comments can be placed at the end of a line, and Python will ignore the rest of
the line:

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


o/p:

Hello, World!

Multi Line Comments

Python does not really have a syntax for multi line comments.

To add a multiline comment you could insert a # for each line:

Or, not quite as intended, you can use a multiline string.

Since Python will ignore string literals that are not assigned to a variable, you can
add a multiline string (triple quotes) in your code, and place your comment inside
it:

Example

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

o/p:

Hello, World!

Python Data Types


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:
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

Getting the Data Type


You can get the data type of any object by using the type() function:

Example

Print the data type of the variable x:

x=5
print(type(x))

o/p:

int

Setting the Data Type


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

x = "Hello World"

#display x:
print(x)

#display the data type of x:


print(type(x))
o/p:

Hello World
<class 'str'>

Python Numbers
There are three numeric types in Python:

 int
 float
 complex

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

Example

x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))

o/p:

<class 'int'>
<class 'float'>
<class 'complex'>

Python List:
Python lists are one of the most versatile data types that allow us to work with multiple elements at
once. For example,

# a list of programming languages


['Python', 'C++', 'JavaScript']

Create Python Lists


In Python, a list is created by placing elements inside square brackets [], separated by commas.

# list of integers
my_list = [1, 2, 3]

A list can have any number of items and they may be of different types (integer, float, string,
etc.).

# empty list
my_list = []

# list with mixed data types


my_list = [1, "Hello", 3.4]

A list can also have another list as an item. This is called a nested list.

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

Access List Elements


There are various ways in which we can access the elements of a list.
List Index

We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a
list having 5 elements will have an index from 0 to 4.Nested lists are accessed using nested
indexing.
Output

p
o
e
a
5
Traceback (most recent call last):
File "<string>", line 21, in <module>
TypeError: list indices must be integers or slices, not float

Negative indexing

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to
the second last item and so on.

# Negative indexing in lists


my_list = ['p','r','o','b','e']

# last item
print(my_list[-1])

# fifth last item


print(my_list[-5])

Output

e
p

List indexing in Python


List Slicing in Python
We can access a range of items in a list by using the slicing operator :.

# List slicing in Python

my_list = ['p','r','o','g','r','a','m','i','z']

# elements from index 2 to index 4


print(my_list[2:5])

# elements from index 5 to end


print(my_list[5:])

# elements beginning to end


print(my_list[:])

Output

['o', 'g', 'r']


['a', 'm', 'i', 'z']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']

Delete List Elements


We can delete one or more items from a list using the Python del statement. It can even delete
the list entirely.

# Deleting list items


my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']

# delete one item


del my_list[2]

print(my_list)

# delete multiple items


del my_list[1:5]

print(my_list)

# delete the entire list


del my_list

# Error: List not defined


print(my_list)

Output

['p', 'r', 'b', 'l', 'e', 'm']


['p', 'm']
Traceback (most recent call last):
File "<string>", line 18, in <module>
NameError: name 'my_list' is not defined

We can use remove () to remove the given item or pop () to remove an item at the given index.
The pop () method removes and returns the last item if the index is not provided. This helps us
implement lists as stacks (first in, last out data structure).
And, if we have to empty the whole list, we can use the clear () method.
Finally, we can also delete items in a list by assigning an empty list to a slice of elements.

>>> my_list = ['p','r','o','b','l','e','m']


>>> my_list[2:3] = []
>>> my_list
['p', 'r', 'b', 'l', 'e', 'm']
>>> my_list[2:5] = []
>>> my_list
['p', 'r', 'm']

Python List Methods


Python has many useful list methods that makes it really easy to work with lists.
Here are some of the commonly used list methods.
Methods Descriptions

append() adds an element to the end of the list

extend() adds all elements of a list to another list


insert() inserts an item at the defined index

remove() removes an item from the list

pop() returns and removes an element at the given index

clear() removes all items from the list

index() returns the index of the first matched item

returns the count of the number of items passed as an


count()
argument

sort() sort items in a list in ascending order

reverse() reverse the order of items in the list

copy() returns a shallow copy of the list

Python Tuple
Creating a Tuple

A tuple is created by placing all the items (elements) inside parentheses (), separated by commas.
The parentheses are optional, however, it is a good practice to use them.

A tuple can have any number of items and they may be of different types (integer, float,
list, string, etc.).

# Different types of tuples

# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers


my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes


my_tuple = (1, "Hello", 3.4)
print(my_tuple)

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

Output

()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))

A tuple can also be created without using parentheses. This is known as tuple packing.

my_tuple = 3, 4.6, "dog"


print(my_tuple)

# tuple unpacking is also possible


a, b, c = my_tuple

print(a) #3
print(b) # 4.6
print(c) # dog

Output

(3, 4.6, 'dog')


3
4.6
dog
Access Tuple Elements

There are various ways in which we can access the elements of a tuple.

1. Indexing

We can use the index operator [] to access an item in a tuple, where the index starts from 0.

So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an index outside of
the tuple index range(6,7,... in this example) will raise an IndexError.

The index must be an integer, so we cannot use float or other types. This will result in TypeError.

Likewise, nested tuples are accessed using nested indexing, as shown in the example below.

# Accessing tuple elements using indexing


my_tuple = ('p','e','r','m','i','t')

print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'

# IndexError: list index out of range


# print(my_tuple[6])

# Index must be an integer


# TypeError: list indices must be integers, not float
# my_tuple[2.0]

# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) #4

Output

p
t
s
4
2. Negative Indexing

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on.

# Negative indexing for accessing tuple elements


my_tuple = ('p', 'e', 'r', 'm', 'i', 't')

# Output: 't'
print(my_tuple[-1])

# Output: 'p'
print(my_tuple[-6])

Output:

3. Slicing

We can access a range of items in a tuple by using the slicing operator colon :.

# Accessing tuple elements using slicing


my_tuple = ('p','r','o','g','r','a','m','i','z')

# elements 2nd to 4th


# Output: ('r', 'o', 'g')
print(my_tuple[1:4])

# elements beginning to 2nd


# Output: ('p', 'r')
print(my_tuple[:-7])

# elements 8th to end


# Output: ('i', 'z')
print(my_tuple[7:])

# elements beginning to end


# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[:])

Output

('r', 'o', 'g')


('p', 'r')
('i', 'z')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

Slicing can be best visualized by considering the index to be between the elements as shown below.
So if we want to access a range, we need the index that will slice the portion from the tuple.

Element Slicing in Python


Changing a Tuple

Unlike lists, tuples are immutable.

This means that elements of a tuple cannot be changed once they have been assigned. But, if
the element is itself a mutable data type like a list, its nested items can be changed.

We can also assign a tuple to different values (reassignment).

# Changing tuple values


my_tuple = (4, 2, 3, [6, 5])

# TypeError: 'tuple' object does not support item assignment


# my_tuple[1] = 9

# However, item of mutable element can be changed


my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5])
print(my_tuple)
# Tuples can be reassigned
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)

Output

(4, 2, 3, [9, 5])


('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

We can use + operator to combine two tuples. This is called concatenation.

We can also repeat the elements in a tuple for a given number of times using the * operator.

Both + and * operations result in a new tuple.

# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))

# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)

Output
(1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')

Tuple Operations
1. Tuple Membership Test

We can test if an item exists in a tuple or not, using the keyword in.

# Membership test in tuple


my_tuple = ('a', 'p', 'p', 'l', 'e',)

# In operation
print('a' in my_tuple)
print('b' in my_tuple)
# Not in operation
print('g' not in my_tuple)

Output
True
False
True

2. Iterating Through a Tuple

We can use a for loop to iterate through each item in a tuple.

# Using a for loop to iterate through a tuple


for name in ('John', 'Kate'):
print("Hello", name)

Output
Hello John
Hello Kate

Python Sets:
A set is an unordered collection of items. Every set element is unique (no duplicates) and must
be immutable (cannot be changed).

However, a set itself is mutable. We can add or remove items from it.

Sets can also be used to perform mathematical set operations like union, intersection, symmetric
difference, etc.

Creating Python Sets


A set is created by placing all the items (elements) inside curly braces {}, separated by comma, or
by using the built-in set() function.

It can have any number of items and they may be of different types (integer, float, tuple, string
etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements.
# Different types of sets in Python
# set of integers
my_set = {1, 2, 3}
print(my_set)

# set of mixed datatypes


my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

Output
{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}
# set cannot have duplicates
# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
# we can make set from a list
# Output: {1, 2, 3}
my_set = set([1, 2, 3, 2])
print(my_set)

# set cannot have mutable items


# here [3, 4] is a mutable list
# this will cause an error.

my_set = {1, 2, [3, 4]}

Output
{1, 2, 3, 4}
{1, 2, 3}
Traceback (most recent call last):
File "<string>", line 15, in <module>
my_set = {1, 2, [3, 4]}
TypeError: unhashable type: 'list'

Python Dictionary
Python dictionary is an unordered collection of items. Each item of a dictionary has
a key/value pair.
Dictionaries are optimized to retrieve values when the key is known.

Creating Python Dictionary


Creating a dictionary is as simple as placing items inside curly braces {} separated by commas.

An item has a key and a corresponding value that is expressed as a pair (key: value).

While the values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.

# empty dictionary
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()
my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair


my_dict = dict([(1,'apple'), (2,'ball')])

Accessing Elements from Dictionary


While indexing is used with other data types to access values, a dictionary uses keys. Keys can be
used either inside square brackets [] or with the get() method.

If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary. On
the other hand, the get() method returns None if the key is not found.

# get vs [] for retrieving elements


my_dict = {'name': 'Jack', 'age': 26}

# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))

# Trying to access keys which doesn't exist throws error


# Output None
print(my_dict.get('address'))

# KeyError
print(my_dict['address'])

Output
Jack
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>
print(my_dict['address'])
KeyError: 'address'

Changing and Adding Dictionary elements


Dictionaries are mutable. We can add new items or change the value of existing items using an
assignment operator.

If the key is already present, then the existing value gets updated. In case the key is not present,
a new (key: value) pair is added to the dictionary.

# Changing and adding Dictionary Elements


my_dict = {'name': 'Jack', 'age': 26}

# update value
my_dict['age'] = 27

#Output: {'age': 27, 'name': 'Jack'}


print(my_dict)

# add item
my_dict['address'] = 'Downtown'
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
print(my_dict)

Output
{'name': 'Jack', 'age': 27}
{'name': 'Jack', 'age': 27, 'address': 'Downtown'}

Removing elements from Dictionary


We can remove a particular item in a dictionary by using the pop() method. This method removes
an item with the provided key and returns the value.

The popitem () method can be used to remove and return an arbitrary (key, value) item pair from
the dictionary. All the items can be removed at once, using the clear () method.

We can also use the del keyword to remove individual items or the entire dictionary itself.

# Removing elements from a dictionary

# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# remove a particular item, returns its value


# Output: 16
print (squares.pop(4))

# Output: {1: 1, 2: 4, 3: 9, 5: 25}


print(squares)

# remove an arbitrary item, return (key,value)


# Output: (5, 25)
print(squares.popitem())

# Output: {1: 1, 2: 4, 3: 9}
print(squares)

# remove all items


squares.clear()

# Output: {}
print(squares)

# delete the dictionary itself


del squares

# Throws Error
print(squares)

Output

16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9}
{}
Traceback (most recent call last):
File "<string>", line 30, in <module>
print(squares)
NameError: name 'squares' is not defined
SAMPLE PYTHON PROGRAMS

1. Write a program in python to take the input from the user and find the sum,
difference, product, division, Modulus and power.

# Take input from the user


a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))

# Perform basic arithmetic operations


sum_result = a + b
difference_result = a - b
product_result = a * b
division_result = a / b
modulus_result = a % b
power_result = a ** b

# Print the results


print("\nResults:")
print("Sum:", sum_result)
print("Difference:", difference_result)
print("Product:", product_result)
print("Division:", division_result)
print("Modulus:", modulus_result)
print("Power:", power_result)

2. Write a program in python to convert Celsius to Fahrenheit.

# Function to convert Celsius to Fahrenheit


def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32

# Take input from the user in Celsius


celsius_temperature = float(input("Enter temperature in Celsius: "))

# Call the conversion function


fahrenheit_temperature = celsius_to_fahrenheit(celsius_temperature)
# Print the result
print(f"{celsius_temperature} Celsius is equal to {fahrenheit_temperature}
Fahrenheit.")

3. Program to find the ASCII value of the given character

# Take input from the user (a single character)


char = input("Enter a character: ")

# Check if the input is a single character


if len(char) == 1:
# Find the ASCII value using ord()
ascii_value = ord(char)
print(f"The ASCII value of '{char}' is {ascii_value}.")
else:
print("Please enter a single character.")

4. Swap two integer numbers using a temporary variable. Repeat the exercise
using the code format: a, b = b, a. Verify your results in both the cases.

# Python swap program


x = input('Enter value of x: ')
y = input('Enter value of y: ')

# create a temporary variable and swap the values


temp = x
x=y
y = temp

print('The value of x after swapping: {}'.format(x))


print('The value of y after swapping: {}'.format(y))
Output:
Enter value of x: 4
Enter value of y: 6
The value of x after swapping: 6
The value of y after swapping: 4
Check the above program with the following code

x, y = y, x
print("x =", x)
print("y =", y)

Output:

x=6
y=4

You might also like