0% found this document useful (0 votes)
13 views44 pages

Pychapt2 New

The document provides an overview of data types, variables, expressions, statements, and control structures in Python. It explains the concept of variables and constants, their declaration and assignment, and various data types such as numeric, strings, lists, tuples, dictionaries, and sets. Additionally, it covers user input, output formatting, and error correction in Python programming.

Uploaded by

sekije2809
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)
13 views44 pages

Pychapt2 New

The document provides an overview of data types, variables, expressions, statements, and control structures in Python. It explains the concept of variables and constants, their declaration and assignment, and various data types such as numeric, strings, lists, tuples, dictionaries, and sets. Additionally, it covers user input, output formatting, and error correction in Python programming.

Uploaded by

sekije2809
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/ 44

MIT College of C.S. & I.T.

, Basmath

Unit-II
Data Types, Variables, Expressions, Statements and
Control Structures
Employing Variables:-

Variable:-
In most of the programming languages a variable is a named location used to store data in
the memory. Each variable must have a unique name called identifier. It is helpful to think
of variables as container that holds data which can be changed later throughout
programming

Declaring Variables in Python

In Python, variables do not need declaration to reserve memory space. The "variable
declaration" or "variable initialization" happens automatically when we assign a value to a
variable.

Assigning value to a Variable in Python

You can use the assignment operator = to assign the value to a variable.

Example 1: Declaring and assigning a value to a variable


website = "Apple.com"

print(website)

When you run the program, the output will be:


Apple.com

In the above program, we assigned a value Apple.com to the variable website. Then we print
the value assigned to website i.e Apple.com

Constants:-
A constant is a type of variable whose value cannot be changed. It is helpful to think of
constants as containers that hold information which cannot be changed later.

Non technically, you can think of constant as a bag to store some books and those books
cannot be replaced once placed inside the bag.

Assigning value to a constant in Python

In Python, constants are usually declared and assigned on a module. Here, the module
means a new file containing variables, functions etc which is imported to main file. Inside the
module, constants are written in all capital letters and underscores separating the words.

Prof. Gajendra D. Dhole 1


MIT College of C.S. & I.T., Basmath
Example 3: Declaring and assigning value to a constant

Create a constant.py

PI = 3.14
GRAVITY = 9.8

Create a main.py

import constant

print(constant.PI)
print(constant.GRAVITY)

When you run the program, the output will be:

3.14
9.8

In the above program, we create a constant.py module file. Then, we assign the constant
value to PI and GRAVITY. After that, we create a main.py file and import the constant
module. Finally, we print the constant value.

Note: In reality, we don't use constants in Python. The globals or constants module is used
throughout the Python programs.

Rules and Naming convention for variables and constants

1. Create a name that makes sense. Suppose, vowel makes more sense than v.
2. Use camelCase notation to declare a variable. It starts with lowercase letter. For
example:
3. myName
4. myAge;
myAddress

5. Use capital letters where possible to declare a constant. For example:


6. PI
7. G
8. MASS
TEMP

9. Never use special symbols like !, @, #, $, %, etc.


10. Don't start name with a digit.
11. Constants are put into Python modules and meant not be changed.
12. Constant and variable names should have combination of letters in lowercase (a to z)
or uppercase (A to Z) or digits (0 to 9) or an underscore (_). For example:
13. snake_case
14. MACRO_CASE
15. camelCase
CapWords

Prof. Gajendra D. Dhole 2


MIT College of C.S. & I.T., Basmath
Data types in Python:-

Numeric:-
Python supports the usual numeric types (integer, long integer, floating and complex
numbers). Programming support, including a complex number type, an unlimited precision
integer.

Integers:- The number four (4) is an example of a numeric value. In mathematics, 4 is an


integer value. Integers are whole numbers, which means they have no fractional parts, and
they can be positive, negative, or zero.

Examples of integers include 4, −19, 0, and −1005. Integers can be of any length, it is only
limited by the memory available.

Float: - Floating-point numbers are an approximation of mathematical real numbers. The


range of floating point number is accurate up to 15 decimal places. Integer and floating
points are separated by decimal points. 1 is integer, 1.0 is floating point number.

Long integers:-
Now for something more exotic: here's a look at long integers in action. When an integer
constant ends with an L (or lowercase l), Python creates a long integer, which can be
arbitrarily big:
>>> 9999999999999999999999999999 + 1
Overflow Error: integer literal too large
>>> 9999999999999999999999999999L + 1
10000000000000000000000000000L

Complex numbers:-
Python complex constants are written as real-part + imaginary-part, and terminated with a j
or J. Internally, they are implemented as a pair of floating-point numbers, but all numeric
operations perform complex math when applied to complex numbers.

Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part. Here are some examples.

>>> c = 1+2j
>>> c
(1+2j)
Strings:-
String an ordered collection of characters, used to store and represent text-based
information. From a functional perspective, strings can be used to represent just about
anything that can be encoded as text: symbols and words (e.g., your name), contents of text
files loaded into memory, and so on.

We can use single quotes or double quotes to represent strings. Multi-line strings can be
denoted using triple quotes, ''' or """.

>>> s = "This is a string"


>>> s = '''a multiline

Boolean values:-
Finally, we should mention the boolean type. This is a value which is either True or False.

Prof. Gajendra D. Dhole 3


MIT College of C.S. & I.T., Basmath
>>> True
True
>>> type( True)
<type ’bool ’>
>>> False
False
>>> type( False )
<type ’bool ’>
Boolean types are used in making decisions.

List :-( array)


List is an ordered sequence of items. It is one of the most used data type in Python and is
very flexible. All the items in a list do not need to be of the same type. Declaring a list is
pretty straight forward. Items separated by commas are enclosed within brackets [ ].

>>> a = [1, 2.2, 'python']

We can use the slicing operator [ ] to extract an item or a range of items from a list. Index
starts form 0 in Python.

a = [5,10,15,20,25,30,35,40]

# a[2] = 15
print("a[2] = ", a[2])

# a[0:3] = [5, 10, 15]


print("a[0:3] = ", a[0:3])

# a[5:] = [30, 35, 40]


print("a[5:] = ", a[5:])

Lists are mutable, meaning; value of elements of a list can be altered.

>>> a = [1,2,3]
>>> a[2]=4
>>> a
[1, 2, 4]

Tuple:-
Tuple is an ordered sequence of items same as list. The only difference is that tuples are
immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than list as it cannot change
dynamically.

It is defined within parentheses () where items are separated by commas.

>>> t = (5,'program', 1+3j)

We can use the slicing operator [] to extract items but we cannot change its value.

t = (5,'program', 1+3j)

Prof. Gajendra D. Dhole 4


MIT College of C.S. & I.T., Basmath
# t[1] = 'program'
print("t[1] = ", t[1])

# t[0:3] = (5, 'program', (1+3j))


print("t[0:3] = ", t[0:3])

# Generates error
# Tuples are immutable
t[0] = 10

Dictionary:-
Dictionary is an unordered collection of key-value pairs.
It is generally used when we have a huge amount of data. Dictionaries are optimized for
retrieving data. We must know the key to retrieve the value.

In Python, dictionaries are defined within braces {} with each item being a pair in the form
key: value. Key and value can be of any type.

>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>

We use key to retrieve the respective value. But not the other way around.

d = {1:'value','key':2}
print(type(d))

print("d[1] = ", d[1]);


value

print("d['key'] = ", d['key']);

2
>>>>d1={‘food’:’spam’,’test’:’ym’}
>>>>d2={1:’Python’,2:’JSP’,3:’c#’}

Set:-
Set is an unordered collection of unique items. Set is defined by values separated by comma
inside braces { }. Items in a set are not ordered.

a = {5,2,3,1,4}

# printing set variable


print("a = ", a)

# data type of variable a


print(type(a))

We can perform set operations like union, intersection on two sets. Set have unique values.
They eliminate duplicates.

>>> a = {1,2,2,3,3,3}
>>> a
{1, 2, 3}
Prof. Gajendra D. Dhole 5
MIT College of C.S. & I.T., Basmath
Since, set are unordered collection, indexing has no meaning. Hence the slicing operator []
does not work.

>>> a = {1,2,3}
>>> a[1]

Traceback (most recent call last):


File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>

TypeError: 'set' object does not support indexing.

Obtaining user Input, Output:-

Output function:-

We use the print() function to output data to the standard output device (screen).

We can also output data to a file, but this will be discussed later. An example use is given
below.

print('This sentence is output to the screen')


# Output: This sentence is output to the screen
a=5

print('The value of a is', a)


# Output: The value of a is 5

In the second print() statement, we can notice that a space was added between the string
and the value of variable a. This is by default, but we can change it.

The actual syntax of the print() function is

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Here, objects is the value(s) to be printed.

The sep separator is used between the values. It defaults into a space character.

After all values are printed, end is printed. It defaults into a new line.

The file is the object where the values are printed and its default value is sys.stdout (screen).
Here are an example to illustrate this.

print(1,2,3,4)
# Output: 1 2 3 4

print(1,2,3,4,sep='*')
# Output: 1*2*3*4

print(1,2,3,4,sep='#',end='&')
# Output: 1#2#3#4&

Prof. Gajendra D. Dhole 6


MIT College of C.S. & I.T., Basmath
Output formatting

Sometimes we would like to format our output to make it look attractive. This can be done by
using the str.format() method. This method is visible to any string object.

>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10

Here the curly braces {} are used as placeholders. We can specify the order in which it is
printed by using numbers (tuple index).

print('I love {0} and {1}'.format('bread','butter'))


# Output: I love bread and butter

print('I love {1} and {0}'.format('bread','butter'))


# Output: I love butter and bread

We can even use keyword arguments to format the string.

>>> print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John'))


Hello John, Goodmorning

We can even format strings like the old sprintf() style used in C programming language. We
use the % operator to accomplish this.

>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457

Input function:-

Up till now, our programs were static. The value of variables were defined or hard coded into
the source code.

To allow flexibility we might want to take the input from the user. In Python, we have the
input() function to allow this. The syntax for input() is

input([prompt])

where prompt is the string we wish to display on the screen. It is optional.

>>> num = input('Enter a number: ')


Enter a number: 10
>>> num
'10'

Here, we can see that the entered value 10 is a string, not a number. To convert this into a
number we can use int() or float() functions.

Prof. Gajendra D. Dhole 7


MIT College of C.S. & I.T., Basmath
>>> int('10')
10
>>> float('10')
10.0

This same operation can be performed using the eval() function. But it takes it further. It can
evaluate even expressions, provided the input is a string

>>> int('2+3')

Traceback (most recent call last):


File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2+3'

>>> eval('2+3')
5

Correcting Errors:-
When coding programs there are three common types of error that can occur. It is useful to
recognize these different error types in Python programming so they can be corrected more
easily:

 Syntax Error – occurs when the interpreter encounters code that does not conform
to the Python language rules. For example, a missing quote mark around a string.
The interpreter halts and reports the error without executing the program.
 Runtime Error – occurs during execution of the program, at the time when the
program runs. For example, when a variable name is later mis-typed so the variable
cannot be recognized. The interpreter runs the program but halts at the error and
reports the nature of the error as an “Exception”.
 Semantic Error – occurs when the program performs unexpectedly. For example,
when order precedence has not been specified in an expression. The interpreter runs
the program and does not report an error.

Correcting syntax and runtime errors is fairly straightforward, as the interpreter reports where
the error occurred or the nature of the error type, but semantic errors require code
examination.

Programming errors are often called “bugs” and the process of tracking them down is often
called “debugging”.

Step 1
Open an IDLE Edit Window then add a statement to output a string that omits a closing
quote mark
print( ‘Coding for Beginners in easy steps )

Step 2
Save then run the program to see the interpreter highlight the syntax error and indicate its
nature

Prof. Gajendra D. Dhole 8


MIT College of C.S. & I.T., Basmath

Step 3
Insert a quote mark before the closing parenthesis to terminate the string and save then run
the program again – to see the error has been corrected

Step 4
Next, begin a new program by initializing a variable then try to output its value with an
incorrect variable name – to see the interpreter report a runtime error
title = ‘Coding for Beginners in easy steps’
print( titel )

Step 5
Amend the variable name to match that in the variable declaration and save then run the
program again – to see the error has been corrected

Step 6
Now, begin a new program by initializing a variable then try to output an expression using its
value without explicit precedence – to see a possibly unexpected result of 28
num = 3
print( ‘Result: ‘ , num * 8 + 4 )

Prof. Gajendra D. Dhole 9


MIT College of C.S. & I.T., Basmath
Step 7

Add parentheses to group the expression as 3 * ( 8 + 4 ) then save the file and run the
program again – to see the expected result of 36, correcting the semantic error

… and it’s as easy as that!

Performing Operations Doing Arithmetic:-


Operators are special symbols in Python that carry out arithmetic or logical computation. The
value that the operator operates on is called the operand.

For example: 2+3=5

Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output
of the operation.

Arithmetic operators:-

Operator Meaning Example


x+y
+ Add two operands or unary plus
+2
x-y
- Subtract right operand from the left or unary minus
-2
* Multiply two operands x*y
/ Divide left operand by the right one (always results into float) x/y
x % y (remainder
% Modulus - remainder of the division of left operand by the right
of x/y)
Floor division - division that results into whole number
// x // y
adjusted to the left in the number line
x**y (x to the
** Exponent - left operand raised to the power of right
power y)

Comparing Values:-
Comparison operators:-
Comparison operators are used to compare values. It either returns True or False according
to the condition.
Comparison operators in Python
Prof. Gajendra D. Dhole 10
MIT College of C.S. & I.T., Basmath
Operator Meaning Example
> Greater that - True if left operand is greater than the right x>y
< Less that - True if left operand is less than the right x<y
== Equal to - True if both operands are equal x == y
!=/<> Not equal to - True if operands are not equal x != y
Greater than or equal to - True if left operand is greater than or equal to
>= x >= y
the right
Less than or equal to - True if left operand is less than or equal to the
<= x <= y
right

Assigning Logic:-

Logical operators:- Logical operators are and, or, not operators.

Logical operators in Python


Operator Meaning Example
and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x

Bitwise operators:-

Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit,
hence the name.

For example, 2 is 10 in binary and 7 is 111.


In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Bitwise operators in Python


Operator Meaning Example
& Bitwise AND x& y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x>> 2 = 2 (0000 0010)
<< Bitwise left shift x<< 2 = 40 (0010 1000)

Assigning Values:-

Assignment operators:-

Assignment operators are used in Python to assign values to variables. a = 5 is a simple


assignment operator that assigns the value 5 on the right to the variable a on the left.

There are various compound operators in Python like a += 5 that adds to the variable and
later assigns the same. It is equivalent to a = a + 5.

Prof. Gajendra D. Dhole 11


MIT College of C.S. & I.T., Basmath
Assignment operators in Python

Operator Example Equivalent to


= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5

Special operators:-

Python language offers some special type of operators like the identity operator or the
membership operator. They are described below with examples.

Identity operators
is and is not are the identity operators in Python. They are used to check if two values (or
variables) are located on the same part of the memory. Two variables that are equal does
not imply that they are identical

Identity operators in Python


Operator Meaning Example
is True if the operands are identical (refer to the same object) x is True
True if the operands are not identical (do not refer to the same x is not
is not
object) True

Membership operators

in and not in are the membership operators in Python. They are used to test whether a
value or variable is found in a sequence (string, list, tuple, set and dictionary).

In a dictionary we can only test for presence of key, not the value.

Operator Meaning Example


in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x

Prof. Gajendra D. Dhole 12


MIT College of C.S. & I.T., Basmath
Examining Conditions:-

Python supports the usual logical conditions from mathematics:

 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.

Example

If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")

In this example we use two variables, a and b, which are used as part of the if statement to
test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than
33, and so we print to screen that "b is greater than a".

Elif

The elif keyword is pythons way of saying "if the previous conditions were not true, then try
this condition".

Example

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

In this example a is equal to b, so the first condition is not true, but the elif condition is true,
so we print to screen that "a and b are equal".

Else

The else keyword catches anything which isn't caught by the preceding conditions.

Prof. Gajendra D. Dhole 13


MIT College of C.S. & I.T., Basmath
Example

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

In this example a is greater than b, so the first condition is not true, also the elif condition is
not true, so we go to the else condition and print to screen that "a is greater than b".

You can also have an else without the elif:

Example

a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
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")

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

Example

One line if else statement, with 3 conditions:


Prof. Gajendra D. Dhole 14
MIT College of C.S. & I.T., Basmath
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")

And

The and keyword is a logical operator, and is used to combine conditional statements:

Example

Test if a is greater than b, AND if c is greater than a:

a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")

Or

The or keyword is a logical operator, and is used to combine conditional statements:

Example

Test if a is greater than b, OR if a is greater than c:

a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")

Nested If

You can have if statements inside if statements, this is called nested if statements.

Example

x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

Prof. Gajendra D. Dhole 15


MIT College of C.S. & I.T., Basmath
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.

Example

a = 33
b = 200

if b > a:
pass

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")

Setting precedence:-
The following table lists all operators from highest precedence to lowest.

Operator Description

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method names for the last

two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>> << Right and left bitwise shift

& Bitwise 'AND'

^| Bitwise exclusive `OR' and regular `OR'

<= < > >= Comparison operators

Prof. Gajendra D. Dhole 16


MIT College of C.S. & I.T., Basmath

<> == != Equality operators

= %= /= //= -= += Assignment operators


*= **=

is is not Identity operators

in not in Membership operators

not or and Logical operators

Operator precedence affects how an expression is evaluated.


For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first multiplies 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom.

Example
#!/usr/bin/python

a = 20
b = 10
c = 15
d = 5
e = 0

e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e

e = ((a + b) * c) / d # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ", e

e = (a + b) * (c / d); # (30) * (15/5)


print "Value of (a + b) * (c / d) is ", e

e = a + (b * c) / d; # 20 + (150/5)
print "Value of a + (b * c) / d is ", e

When you execute the above program, it produces the following result –

Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50

Prof. Gajendra D. Dhole 17


MIT College of C.S. & I.T., Basmath
Casting data types:-

We can convert between different data types by using different type conversion functions like
int(), float(), str() etc.

>>> float(5)
5.0

Conversion from float to int will truncate the value (make it closer to zero).

>>> int(10.6)
10
>>> int(-10.6)
-10

Conversion to and from string must contain compatible values.

>>> float('2.5')
2.5
>>> str(25)
'25'
>>> int('1p')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1p'

We can even convert one sequence to another.

>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']

To convert to dictionary, each element must be a pair

>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}

Expressions:-

An expression is a combination of values, variables, and operators. A value all by itself is


considered an expression, and so is a variable, so the following are all legal expressions
(assuming that the variable x has been assigned a value):
17
x
x + 17
Prof. Gajendra D. Dhole 18
MIT College of C.S. & I.T., Basmath
If you type an expression in interactive mode, the interpreter evaluates it and displays the
result:
>>> 1 + 1
2
But in a script, an expression all by itself doesn’t do anything! This is a common source of
confusion for beginners.

Statements:-
A statement is a unit of code that the Python interpreter can execute. We have seen two
kinds of statements: print and assignment. When you type a statement in interactive mode,
the interpreter executes it and displays the result, if there is one.

A script usually contains a sequence of statements. If there is more than one statement, the
results appear one at a time as the statements execute.

For example, the script


print 1
x=2
print x
produces the output
1
2
The assignment statement produces no output.

Assignment statements:-

An assignment statement in Python has the form variable = expression. This has the
following effect. First the expression on the right hand side is evaluated, then the result is
assigned to the variable. After the assignment, the variable becomes a name for the result.

The variable retains the same value until another value is assigned, in which case the
previous value is lost.

Executing the assignment produces no output; its purpose it to make the association
between the variable and its value.
>>> x = 2+2
>>> print x
4
In the example above, the assignment statement sets x to 4, producing no output.

Python Indentation:-
Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation.

A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent throughout
that block.
Generally four whitespaces are used for indentation and is preferred over tabs. Here is an
example.
for i in range(1,11):
print(i)
if i == 5:
break
Prof. Gajendra D. Dhole 19
MIT College of C.S. & I.T., Basmath

The enforcement of indentation in Python makes the code look neat and clean. This results
into Python programs that look similar and consistent.

Indentation can be ignored in line continuation. But it's a good idea to always indent. It
makes the code more readable.

For example:

if True:
print('Hello')
a = 5

and

if True: print('Hello'); a = 5

both are valid and do the same thing. But the former style is clearer.
Incorrect indentation will result into IndentationError.

Python Comments:-

Comments are very important while writing a program. It describes what's going on inside a
program so that a person looking at the source code does not have a hard time figuring it out.
You might forget the key details of the program you just wrote in a month's time. So taking
time to explain these concepts in form of comments is always fruitful.

In Python, we use the hash (#) symbol to start writing a comment.

It extends up to the newline character. Comments are for programmers for better
understanding of a program. Python Interpreter ignores comment.

#This is a comment
#print out Hello
print('Hello')

Multi-line comments

If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the
beginning of each line. For example:

#This is a long comment


#and it extends
#to multiple lines

Another way of doing this is to use triple quotes, either ''' or """.

These triple quotes are generally used for multi-line strings. But they can be used as multi-
line comment as well. Unless they are not docstrings, they do not generate any extra code.

"""This is also a
perfect example of
multi-line comments"""

Prof. Gajendra D. Dhole 20


MIT College of C.S. & I.T., Basmath
Python Import:-
When our program grows bigger, it is a good idea to break it into different modules.

A module is a file containing Python definitions and statements. Python modules have a
filename and end with the extension .py.

Definitions inside a module can be imported to another module or the interactive interpreter
in Python. We use the import keyword to do this.

For example, we can import the math module by typing in import math.

import math
print(math.pi)

Now all the definitions inside math module are available in our scope. We can also import
some specific attributes and functions only, using the from keyword. For example:

>>> from math import pi


>>> pi
3.141592653589793

While importing a module, Python looks at several places defined in sys.path. It is a list of
directory locations.

>>> import sys


>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']

We can add our own location to this list as well.

Branching with if:-


Decision:- If Statement

Decision making is required when we want to execute a code only if a certain condition is
satisfied

If Statement Syntax:-

if test expression:
statement(s)

Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True. If the text expression is False, the statement(s) is not executed.

Prof. Gajendra D. Dhole 21


MIT College of C.S. & I.T., Basmath
In Python, the body of the if statement is indicated by the indentation. Body starts with an
indentation and the first unindented line marks the end.

Python interprets non-zero values as True. None and 0 are interpreted as False

If Statement Flowchart:-

Example:-

num=5

if num > 0:

print(num, ”is a positive number”)

When you run the program, the output will be:

5 is a positive number

if...else Statement:-

If variable num is equal to -1, test expression is false and body inside body of if is skipped.

The print() statement falls outside of the if block (unindented). Hence, it is executed
regardless of the test expression.

Syntax of if...else:-

if test expression:
Body of if
else:
Body of else

The if..else statement evaluates test expression and will execute body of if only
when test condition is True.

If the condition is False, body of else is executed. Indentation is used to separate the
blocks.
Prof. Gajendra D. Dhole 22
MIT College of C.S. & I.T., Basmath
If..else Flowchart:-

Example:-

num=-5

if num > 0:

print (num, ”is a positive number”)

else:

print (num, ”is a negative number”)

When you run the program, the output will be:

-5 is a negative number

if...elif...else Statement:- If num is equal to 0, the test expression is true and body of if is
executed and body of else is skipped.

Syntax of if...elif...else:-

if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
If all the conditions are False, body of else is executed.
Only one block among the several if...elif...else blocks is executed according to the
condition.

Prof. Gajendra D. Dhole 23


MIT College of C.S. & I.T., Basmath
Theif block can have only one else block. But it can have multiple elif blocks.

Flowchart of if...elif...else:-

Example:-

num=5

if num > 0:

print (num, ”is a positive number”)

elif num==0:

print (num, ”is a zero number”)

else:

print (num, ”is a negative number”)

When variable num is positive, Positive number is printed.

If num is equal to 0, Zero is printed.

If num is negative, Negative number is printed

Nested if statements:-

We can have a if...elif...else statement inside another if...elif...else


statement. This is called nesting in computer programming.

Prof. Gajendra D. Dhole 24


MIT College of C.S. & I.T., Basmath
Any number of these statements can be nested inside one another. Indentation is the only
way to figure out the level of nesting. This can get confusing, so must be avoided if we can.

Syntax of nested if....else:-

if test expression:
Body of if
if test expression:
Body of if
else:
Body of else
else:
Body of else

Example:-

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


if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

When you run the program, the output will be

Output1:- Enter a number: 5


Positive number

Output1:- Enter a number: -1


Negative number

Output1:- Enter a number: 0


Zero

Loops:-
for loop:-
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called traversal

Syntax of for Loop:-

for val in sequence:


Body of for

Prof. Gajendra D. Dhole 25


MIT College of C.S. & I.T., Basmath
Here, val is the variable that takes the value of the item inside the sequence on each
iteration.

Loop continues until we reach the last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.

Flowchart of for Loop:-

Example: -

Numbers=[6, 5, 3, 8, 4, 2, 5, 4, 11] #list of numbers

Sum=0

For val in number: #iterate over the list

Sum=sum+val

Print(“The sum is”,sum) # output is 48

when you run the program, the output will be:

The sum is 48

Prof. Gajendra D. Dhole 26


MIT College of C.S. & I.T., Basmath
The range() function:-
We can generate a sequence of numbers using range() function. range(10) will generate
numbers from 0 to 9 (10 numbers).

We can also define the start, stop and step size as range(start,stop,step size). step size
defaults to 1 if not provided.

This function does not store all the values in memory, it would be inefficient. So it
remembers the start, stop, step size and generates the next number on the go.

To force this function to output all the items, we can use the function list().

The following example will clarify this

# Output: range(0, 10)


print(range(10))

# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))

# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))

# Output: [2, 5, 8, 11, 14, 17]


print(list(range(2, 20, 3)))

for loop with else:-

A for loop can have an optional else block as well. The else part is executed if the items in
the sequence used in for loop exhausts.

break statement can be used to stop a for loop. In such case, the else part is ignored.

Hence, a for loop's else part runs if no break occurs.

Here is an example to illustrate this.

Example:-

digits=[0,1,5]

for i in digits:

print(i)

else:

print(“no items left.”)

When you run the program, the output will be:

Prof. Gajendra D. Dhole 27


MIT College of C.S. & I.T., Basmath
0
1
5
No items left.

Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts,
it executes the block of code in the else and prints

No items left.

Looping While true:-


The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is true.

Syntax of while Loop :-

while test_expression:
Body of while

In while loop, test expression is checked first. The body of the loop is entered only if the
test_expression evaluates to True. After one iteration, the test expression is checked
again. This process continues until the test_expression evaluates to False.

In Python, the body of the while loop is determined through indentation.

Body starts with indentation and the first unindented line marks the end.

Python interprets any non-zero value as True. None and 0 are interpreted as False.

Flowchart of while Loop:-

Prof. Gajendra D. Dhole 28


MIT College of C.S. & I.T., Basmath
Example:- n=10

sum=0

i=1

while i<=n

sum=sum+i

print(“the sum is”, sum)

When you run the program, the output will be:

Enter n: 10
The sum is 55

n the above program, the test expression will be True as long as our counter variable i is
less than or equal to n (10 in our program).

We need to increase the value of counter variable in the body of the loop. This is very
important (and mostly forgotten). Failing to do so will result in an infinite loop (never ending
loop).

Finally the result is displayed.

While loop with else:-

Same as that of for loop, we can have an optional else block with while loop as well.
The else part is executed if the condition in the while loop evaluates to False.
The while loop can be terminated with a break statement. In such case, the else part is
ignored. Hence, a while loop's else part runs if no break occurs and the condition is false.

Here is an example to show this.

Example:-

counter =0

while counter < 3:

Print(“Inside loop”)

counter =counter+1

else:

print(“Inside else”)

Output

Inside loop
Inside loop

Prof. Gajendra D. Dhole 29


MIT College of C.S. & I.T., Basmath
Inside loop
Inside else

Here, we use a counter variable to print the string Inside loop three times.

On the forth iteration, the condition in while becomes False. Hence, the else part is
executed.

Looping over items:-


How to loop over Python list variable. Loop through the list variable in Python and print each
element one by one. The short answer is to use the for loop to loop over a List variable and
print it in the output.

You can also use the While loop of Python to traverse through all the elements of the List

variable. The for loop is helpful to get the values within a certain specified range. The list

variable is the variable whose values are comma-separated. All the items are enclosed

within the square brackets ([]). Let’s find out with the examples given below.

1. For Loop Over Python List Variable and Print All Elements
To get only the items and not the square brackets, you have to use the Python for loop.

Inside the for loop, you have to print each item of a variable one by one in each line.

myList = ['Ram', 'Shyam', 10, 'Bilal', 13.2, 'Feroz'];


for x in myList:
print(x);

output

Ram
Shyam
10
Bilal
13.2
Feroz

The above example prints each element of the Python list variable line by line. They are
printed here without any square brackets or quotes. The print statement prints the single
element in each line.

Prof. Gajendra D. Dhole 30


MIT College of C.S. & I.T., Basmath
2. For Loop With Range of Length to Iterate Through List in Python
You can add a range of lengths with for loop of Python. With range, you can print list

elements between the given range. You can print the element in the range whatever you

want.

Below are the different ranges of length to print the elements of the list in Python.

Print All Elements using For Loop Range

If you want to print all the elements of the list in Python. You have to use the below-given

example using the range() function of Python.

Check the below Python coding to print your list element as per your requirement.

myList = ['Ram', 'Shyam', 10, 'Bilal', 13.2, 'Feroz'];


for x in range(len(myList)):
print(myList[x])

output

Ram

Shyam

10

Bilal

13.2

Feroz

The above example prints all the elements of the list element in the output. The above output

contains all the elements with a single element in each line.

3. Print All Element Except Last

To print all the elements of the list variable in Python. You have to use the below-given

example which removes the last element.

Add -1 after the len() function of Python to remove the last element from the output. You

will get all the elements of the list element except the last one.

myList = ['Ram', 'Shyam', 10, 'Bilal', 13.2, 'Feroz'];


for x in range(len(myList)-1):
print(myList[x])

Prof. Gajendra D. Dhole 31


MIT College of C.S. & I.T., Basmath
output

Ram
Shyam
10
Bilal
13.2

The above example prints all the elements except the last one in the Python List variable.

4. Print All Element Except Last Two

To remove more elements from the output with the List element of Python. You have to

increase the value you have added after the len() function of Python.

You can increase this value to remove the number of elements from the output.

myList = ['Ram', 'Shyam', 10, 'Bilal', 13.2, 'Feroz'];


for x in range(len(myList)-2):
print(myList[x])
output

Ram
Shyam
10
Bilal

The above example prints all the elements except the last two list elements.

5. While Loop Through Python List Variable to Print All Element


In addition to the above, you can also use the while loop of Python to access and print

each element. You have to use the below-given example to print all the items of the list

element.

In a while loop, you have to first initialize the variable to start the while loop. Inside the

while loop, you also have to add the same variable with the increment operator.
myList = ['Ram', 'Shyam', 10, 'Bilal', 13.2, 'Feroz'];
x=0;
while x < len(myList):
print(myList[x])
x += 1

output

Ram
Shyam
10
Prof. Gajendra D. Dhole 32
MIT College of C.S. & I.T., Basmath
Bilal
13.2
Feroz

The above example using the while loop and prints all the elements in the output. Each
item of the list element gets printed line by line.

6. For-in Loop to Looping Through Each Element in Python

The for-in loop of Python is the same as the foreach loop of PHP. It prints all the elements of
the list variable in the output. Use the below-given example to print each element using the
for-in loop.
myList = ['Ram', 'Shyam', 10, 'Bilal', 13.2, 'Feroz'];
for List in myList:
print(List)

output

Ram
Shyam
10
Bilal
13.2
Feroz

The above example contains the output which prints all the elements line by line.

Breaking out of loops:-


Normally, a while statement executes until its condition becomes false. This condition is
checked only at the ”top” of the loop, so the loop is not immediately exited if the condition
becomes false due to activity in the middle of the body. Ordinarily this behavior is not a
problem because the intention is to execute all the statements within the body as an
indivisible unit. Sometimes, however, it is desirable to immediately exit the body or recheck
the condition from the middle of the loop instead. Python provides the break and continue
statements to give programmers more flexibility designing the control logic of loops.

The break statement


Python provides the break statement to implement middle-exiting control logic. The break
statement causes the immediate exit from the body of the loop.

Syntax of break:-
Python break statement has very simple syntax where we only use break keyword. We
generally check for a condition with if-else blocks and then use break .
break

Prof. Gajendra D. Dhole 33


MIT College of C.S. & I.T., Basmath
Syntax of Break in for and while loop.
for value in sequence:

# code for for block

if condition:

break

#code for for loop

#outside of for loop

while expression:

#code for while loop

if if_expression:

break

#code for while loop

#outside of while loop

break keyword in python that often used with loops for and while to modify the flow of loops.
Loops are used to execute a statement again and again until the expression
becomes False or the sequence of elements becomes empty. But what if, we want to
terminate the loop before the expression become False or we reach the end of the
sequence, and that’s the situation when the break comes in-game.

In the following example, while loop is set to print the first 8 items in the tuple. But what
actually happens is, when the count is equal to 4, it triggers if statement and
the break statement inside it is invoked making the flow of program jump out of the loop.

#declaring a tuple

num = (1,2,3,4,5,6,7,8)

count = 0

while (count<9):

print (num[count])

count = count+1

Prof. Gajendra D. Dhole 34


MIT College of C.S. & I.T., Basmath
if count == 4:

break

print ('End of program')

Output
1
2
3
4
End of program

Example 2: Python break while loop

i = 0;
while 1:
print(i,” “,end=””),
i=i+1;
if i == 10:
break;
print(“came out of while loop”);

Output:
0 1 2 3 4 5 6 7 8 9 came out of while loop

The continue Statement:-

The continue statement is similar to the break statement. During a program’s execution,
when the break statement is encountered within the body of a loop, the remaining
statements within the body of the loop are skipped, and the loop is exited. When a continue
statement is encountered within a loop, the remaining statements within the body are
skipped, but the loop condition is checked to see if the loop should continue or be exited. If
the loop’s condition is still true, the loop is not exited, but the loop’s execution continues at
the top of the loop.

Example:-
1 sum = 0
2 done = False;
3 while not done:
4 val = eval(input("Enter positive integer (999 quits):"))
5 if val < 0:
6 print("Negative value", val, "ignored")
7 continue; # Skip rest of body for this iteration
8 if val != 999:
9 print("Tallying", val)
10 sum += val
11 else:

Prof. Gajendra D. Dhole 35


MIT College of C.S. & I.T., Basmath
12 done = (val == 999); # 999 entry exits loop
13 print("sum =", sum)

The continue statement is not used as frequently as the break statement since it is often
easy to transform the code into an equivalent form that does not use continue.

Working with List, Tuple, Set, Dictionary:-

List:-
Python offers a range of compound datatypes often referred to as sequences. List is one of
the most frequently used and very versatile datatype used in Python .
create a list

In Python programming, a list is created by placing all the items (elements) inside a square
bracket [ ], separated by commas.

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

# empty list
my_list = []

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

# list with mixed datatypes


my_list = [1, "Hello", 3.4]

Also, a list can even have another list as an item. This is


called nested list.

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

How to access elements from a list?

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. Index starts from 0. So, a list
having 5 elements will have index from 0 to 4.

Trying to access an element other that this will raise an IndexError. The index must be an
integer. We can't use float or other types, this will result into TypeError.

Nested list are accessed using nested indexing.

>>>my_list=['p','r','o','b','e']
>>>print(my_list(0))

Prof. Gajendra D. Dhole 36


MIT College of C.S. & I.T., Basmath
p
>>> print(my_list[2])
o
>>> print(my_list[4])
e
>>> print(my_list[4,0])

Traceback (most recent call last):


File "<pyshell#5>", line 1, in <module>
print(my_list[4,0])
TypeError: list indices must be integers

>>> n_list=["Happy",[2,0,1,5]]
>>> print(n_list[0][1])
a
>>> print(n_list[1][3])
5

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.

>>>my_list=['p','r','o','b','e']
>>>print(my_list[-1])
e
>>>print(my_list[-5])
p

How to slice lists in Python?

We can access a range of items in a list by using the slicing operator (colon).

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

>>> print(my_list[2:5])
['o', 'g', 'r']

>>> print(my_list[:-5])
['p', 'r', 'o']
>>> print(my_list[5:])
['a', 'm', 'z']
>>> print(my_list[:])
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'z']

How to change or add elements to a list?

Prof. Gajendra D. Dhole 37


MIT College of C.S. & I.T., Basmath
List are mutable, meaning, their elements can be changed unlike string or tuple.
We can use assignment operator (=) to change an item or a range of items.

>>> odd=[2,4,6,8]
>>> odd
[2, 4, 6, 8]
>>> odd[0]=1
>>> odd
[1, 4, 6, 8]
>>> odd[1:4]=[3,5,7]
>>> odd
[1, 3, 5, 7]
>>>
We can add one item to a list using append() method or add several items using extend()
method.
odd = [1, 3, 5]

odd.append(7)

# Output: [1, 3, 5, 7]
print(odd)

odd.extend([9, 11, 13])

# Output: [1, 3, 5, 7, 9, 11, 13]


print(odd)

We can also use + operator to combine two lists. This is also called concatenation.
The * operator repeats a list for the given number of times.

odd = [1, 3, 5]

# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])

#Output: ["re", "re", "re"]


print(["re"] * 3)

Furthermore, we can insert one item at a desired location by using the method insert() or
insert multiple items by squeezing it into an empty slice of a list.

>>> odd=[1,9]
>>> odd
[1, 9]
>>> odd.insert(1,3)
>>> odd
[1, 3, 9]
>>> odd[2:2]=[5,7]
>>> odd
[1, 3, 5, 7, 9]
>>>

Prof. Gajendra D. Dhole 38


MIT College of C.S. & I.T., Basmath

How to delete or remove elements from a list?

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

>>> my_list=['p','r','o','g','r','a','m','z']
>>> my_list
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'z']
>>> del my_list[2]
>>> my_list
['p', 'r', 'g', 'r', 'a', 'm', 'z']
>>> del my_list[1:5]
>>> my_list
['p', 'm', 'z']
>>> del my_list
>>> my_list

Traceback (most recent call last):


File "<pyshell#37>", line 1, in <module>
my_list
NameError: name 'my_list' is not defined

We can use remove() method to remove the given item or pop() method to remove an item
at the given index.
The pop() method removes and returns the last item if index is not provided. This helps us
implement lists as stacks (first in, last out data structure).

>>> my_list=['p','r','o','g','r','a','m','z']
>>> my_list.remove('p')
>>> print(my_list)
['r', 'o', 'g', 'r', 'a', 'm', 'z']
>>> print(my_list.pop(1))
o
>>> print(my_list)
['r', 'g', 'r', 'a', 'm', 'z']
>>> print(my_list.pop())
z
>>> print(my_list)
['r', 'g', 'r', 'a', 'm']

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']

Prof. Gajendra D. Dhole 39


MIT College of C.S. & I.T., Basmath

Python List Methods

Methods that are available with list object in Python programming are tabulated below.
They are accessed as list.method(). Some of the methods have already been used above.

Python List Methods


append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of number of items passed as an 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

Dictionary:-

Python dictionary is an unordered collection of items. While other compound data types have
only value as an element, a dictionary has a key: value pair.
Dictionaries are optimized to retrieve values when the key is known.

How to create a dictionary?

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


comma.
An item has a key and the corresponding value expressed as a pair, key: value.

While 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'})

Prof. Gajendra D. Dhole 40


MIT College of C.S. & I.T., Basmath
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])

As you can see above, we can also create a dictionary using the built-in function dict()

How to access elements from a dictionary?

While indexing is used with other container types to access values, dictionary uses keys.
Key can be used either inside square brackets or with the get() method.

The difference while using get() is that it returns None instead of KeyError, if the key is not
found.

. >>> my_dict={'Name':'Jack','Age':26}
>>> print(my_dict)
{'Age': 26, 'Name': 'Jack'}
>>> print(my_dict['Name'])
Jack
>>> print(my_dict.get('Age'))
26
>>> print(my_dict.get('Address'))
None
>>> print(my_dict['Address'])

Traceback (most recent call last):


File "<pyshell#55>", line 1, in <module>
print(my_dict['Address'])
KeyError: 'Address'

How to change or add elements in a dictionary?

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

If the key is already present, value gets updated, else a new key: value pair is added to the
dictionary.

>>> my_dict={'Name':'Jack','Age':26}
>>> print(my_dict)
{'Age': 26, 'Name': 'Jack'}
>>> my_dict['Age']=30
>>> print(my_dict)
{'Age': 30, 'Name': 'Jack'}
>>> my_dict['Address']='Nanded'
>>> print(my_dict)
{'Age': 30, 'Name': 'Jack', 'Address': 'Nanded'}
>>>

How to delete or remove elements from a dictionary?

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

Prof. Gajendra D. Dhole 41


MIT College of C.S. & I.T., Basmath
The method, popitem() can be used to remove and return an arbitrary item (key, value) form
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.

>>> sqr={1:1,2:4,3:9,4:16,5:25}
>>> print(sqr)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
>>> print(sqr.pop(4))
16
>>> print(sqr)
{1: 1, 2: 4, 3: 9, 5: 25}
>>> print(sqr.popitem())
(1, 1)
>>> print(sqr)
{2: 4, 3: 9, 5: 25}
>>> del sqr[5]
>>> print(sqr)
{2: 4, 3: 9}
>>> del sqr
>>> print(sqr)

>>> sqr.clear()
>>> print(sqr)
{}

Python Dictionary Methods

Methods that are available with dictionary are tabulated below. Some of them have already
been used in the above examples.

Method Description
clear() Remove all items form the dictionary.
copy() Return a shallow copy of the dictionary.
fromkeys(seq[, Return a new dictionary with keys from seq and value equal to v (defaults
v]) to None).
get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults to None).
items() Return a new view of the dictionary's items (key, value).
keys() Return a new view of the dictionary's keys.
Remove the item with key and return its value or d if key is not found. If d
pop(key[,d])
is not provided and key is not found, raises KeyError.
Remove and return an arbitary item (key, value). Raises KeyError if the
popitem()
dictionary is empty.
If key is in the dictionary, return its value. If not, insert key with a value of
setdefault(key[,d])
d and return d (defaults to None).
Update the dictionary with the key/value pairs from other, overwriting
update([other])
existing keys.
values() Return a new view of the dictionary's values

Prof. Gajendra D. Dhole 42


MIT College of C.S. & I.T., Basmath

Python Set Methods:-

Set is an unordered collection of unique items. Set is defined by values separated by comma
inside braces { }. Items in a set are not ordered.

a = {5,2,3,1,4}

# printing set variable


print("a = ", a)

We can perform set operations like union, intersection on two sets. Set have unique values.
They eliminate duplicates.

Since, set are unordered collection, indexing has no meaning. Hence the slicing operator []
does not work.

Python has a set of built-in methods that you can use on sets.

Method Description

add() Adds an element to the set

clear() Removes all the elements from the set


copy() Returns a copy of the set
Returns a set containing the difference between two or
difference()
more sets
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two or more sets
pop() Removes an element from the set
remove() Removes the specified element
union() Return a set containing the union of sets
update() Update the set with another set, or any other iterable

Python Tuple Methods:-

Tuple is an ordered sequence of items same as list. The only difference is that tuples are
immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than list as it cannot change
dynamically.

It is defined within parentheses () where items are separated by commas.

Prof. Gajendra D. Dhole 43


MIT College of C.S. & I.T., Basmath
>>> t = (5,'program', 1+3j)

We can use the slicing operator [] to extract items but we cannot change its value.

t = (5,'program', 1+3j)

# t[1] = 'program'
print("t[1] = ", t[1])

# t[0:3] = (5, 'program', (1+3j))


print("t[0:3] = ", t[0:3])

# Generates error
# Tuples are immutable
t[0] = 10

Method Description

count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the position of
where it was found

Prof. Gajendra D. Dhole 44

You might also like