Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 62

Python

Python interpreter and interactive mode; values and types: int, float, boolean, string, and list;
variables, expressions, statements, tuple assignment, precedence of operators, comments; Modules and
functions, function definition and use, flow of execution, parameters and arguments; Illustrative
programs: exchange the values of two variables, circulate the values of n variables, distance between
two points.

INTRODUCTION TO PYTHON:
Python is a general-purpose interpreted, interactive, object-oriented, and high- level programming
language.
It was created by Guido van Rossum during 1985- 1990.
Python got its name from “Monty Python’s flying circus”. Python was released in the
year 2000.
 Python is interpreted: Python is processed at runtime by the interpreter. You
 do not need to compile your program before executing it.
 Python is Interactive: You can actually sit at a Python prompt and interact with
 the interpreter directly to write your programs.
 Python is Object-Oriented: Python supports Object-Oriented style or technique
of programming that encapsulates code within objects.
 Python is a Beginner's Language: Python is a great language for the beginner-
level programmers and supports the development of a wide range of applications.

Easy-to-learn:Python is clearly defined and easily readable. The structure of the program is very simple.
It uses few keywords.

  Easy-to-maintain: Python's source code is fairly easy-to-maintain.


 Portable: Python can run on a wide variety of hardware platforms and has the
 same interface on all platforms.
 Interpreted: Python is processed at runtime by the interpreter. So, there is no
 need to compile a program before executing it. You can simply run the program.
 Extensible: Programmers can embed python within their C,C++,Java script
 ,ActiveX, etc.
 Free and Open Source: Anyone can freely distribute it, read the source code, and
 edit it.
 High Level Language: When writing programs, programmers concentrate on
 solutions of the current problem, no need to worry about the low level details.
 Scalable: Python provides a better structure and support for large programs
than shell scripting.

 Bit Torrent file sharing


Google search engine, Youtube
Intel, Cisco, HP, IBM
 i–Robot
NASA

Facebook, Drop box

Python interpreter:
Interpreter: To execute a program in a high-level language by translating it one line at a time.
Compiler: To translate a program written in a high-level language into a low-level language all at once, in
preparation for later execution.

MODES OF PYTHON INTERPRETER:


Python Interpreter is a program that reads and executes Python code. It uses 2 modes of Execution.
1. Interactive mode
2. Script mode
Interactive mode:
  Interactive Mode, as the name suggests, allows us to interact with OS.
 When we type Python statement, interpreter displays the result(s)
 immediately.
 Advantages:
  Python, in interactive mode, is good enough to learn, experiment or explore.
 Working in interactive mode is convenient for beginners and for testing small
 pieces of code.
 Drawback:
 We cannot save the statements and have to retype all the statements once again to
re-run them.
In interactive mode, you type Python programs and the interpreter displays the result:
>>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you to enter code. If you
type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!') Hello, World!

This is an example of a print statement. It displays a result on the screen. In this case, the result is the
words.

Script mode:
 In script mode, we type python program in a file and then use interpreter to
 execute the content of the file.
 Scripts can be saved to disk for future use. Python scripts have the extension
 .py, meaning that the filename ends with .py
 Save the code with filename.py and run the interpreter in script mode to execute
the script.

Integrated Development Learning Environment (IDLE):


  Is a graphical user interface which is completely written in Python.
 It is bundled with the default implementation of the python language and also
comes with optional part of the Python packaging.
Features of IDLE:
Multi-window text editor with syntax highlighting.

 Auto completion with smart indentation.


 Python shell to display output with syntax highlighting.

.VALUES AND DATA TYPES

Value:
Value can be any letter ,number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different datatypes.)
Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
Python has four standard data types:

Numbers:
  Number data type stores Numerical Values.
  This data type is immutable [i.e. values/items cannot be changed].
 Python supports integers, floating point numbers and complex numbers. They
are defined as,

Sequence:
  A sequence is an ordered collection of items, indexed by positive integers.
 It is a combination of mutable (value can be changed) and immutable (values
cannot be changed) data types.

 There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples

 A String in Python consists of a series or sequence of characters - letters,


 numbers, and special characters.
 Strings are marked by quotes:
 single quotes (' ') Eg, 'This a string in single quotes'
 double quotes (" ") Eg, "'This a string in double quotes'"
 triple quotes(""" """) Eg, This is a paragraph. It is made up of multiple
 lines and sentences."""
  Individual character in a string is accessed using a subscript (index).
 Characters can be accessed using indexing and slicing operations
Strings are immutable i.e. the contents of the string cannot be changed after it is created.
Indexing:

 Positive indexing helps in accessing the string from the beginning


  Negative subscript helps in accessing the string from the end.
 Subscript 0 or –ve n(where n is length of the string) displays the first element.
 Example: A[0] or A[-5] will display “H”
 Subscript 1 or –ve (n-1) displays the second element.

i. Indexing ii. Slicing


iii. Concatenation iv. Repetitions
v. Member ship

Creating a string >>> s="good morning"


Creating the list with elements of different data types.
Indexing >>> print(s[2]) Accessing the item in the
o position 0
>>> print(s[6]) Accessing the item in the
O position 2
Slicing( ending >>> print(s[2:]) - Displaying items from 2nd till
position -1) od morning last.

Slice operator is >>> print(s[:4]) - Displaying items from 1st


used to extract Good position till 3rd .
part of a data type
Concatenation >>>print(s+"friends") -Adding and printing the good morningfriends characters
of two strings.

Repetition >>>print(s*2) Creates new strings, good morninggood


concatenating multiple copies of
morning the same string
in, not in >>> s="good morning" Using membership operators to (membership >>>"m"
in s check a particular character is in operator) True string or
not. Returns true if
>>> "a" not in s present.
True
Lists
  List is an ordered sequence of items. Values in the list are called elements / items.
 It can be written as a list of comma-separated items (values) between square
 brackets[ ].
 Items in the lists can be of different data types.

Tuple:
 A tuple is same as list, except that the set of elements is enclosed in parentheses
 instead of square brackets.
 A tuple is an immutable list. i.e. once a tuple has been created, you can't add
 elements to a tuple or remove elements from the tuple.
  Benefit of Tuple:
 Tuples are faster than lists.
 If the user wants to protect the data from accidental changes, tuple can be used.
 Tuples can be used as keys in dictionaries, while lists can't.

Altering the tuple data type leads to error. Following error occurs when user tries to do.

>>> t[0]="a"
Trace back (most recent call last):
File "<stdin>", line 1, in <module> Type Err

assignment

Mapping

-This data type is unordered and mutable.


-Dictionaries fall under Mappings.
Dictionaries:
  Lists are ordered sets of objects, whereas dictionaries are unordered sets.
 Dictionary is created by using curly brackets. i,e. {}
  Dictionaries are accessed via keys and not via their position.
 A dictionary is an associative array (also known as hashes). Any key of the
 dictionary is associated (or mapped) to a value.
 The values of a dictionary can be any Python data type. So dictionaries are
unordered key-value-pairs(The association of a key and a value is called a key- value pair )
Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and lists.

Data type Compile time Run time


int a=10 a=int(input(“enter a”)) float
a=10.5 a=float(input(“enter a”)) string a=”panimalar”
a=input(“enter a string”) list a=[20,30,40,50] a=list(input(“enter a list”))
tuple a=(20,30,40,50) a=tuple(input(“enter a tuple”))

3.Variables,Keywords Expressions, Statements, Comments, Docstring ,Lines And


Indentation, Quotation In Python, Tuple Assignment:

VARIABLES:
 A variable allows us to store a value by assigning it to a name, which can be used later.
  Named memory locations to store values.
 Programmers generally choose names for their variables that are meaningful.
  It can be of any length. No space is allowed.
 We don't need to declare a variable before using it. In Python, we simply assign a
value to a variable and it will exist.

Assigning value to variable:


Value should be given on the right side of assignment operator(=) and variable on left side.
>>>counter =45 print(counter)

Assigning a single value to several variables simultaneously:

>>> a=b=c=100
Assigning multiple values to multiple variables:

>>> a,b,c=2,4,"ram"

KEYWORDS:
  Keywords are the reserved words in Python.
We cannot use a keyword as variable name, function name or any other
identifier.
  They are used to define the syntax and structure of the Python language.
  Keywords are case sensitive.
IDENTIFIERS:
Identifier is the name given to entities like class, functions, variables etc. in
Python.
 Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A
to Z) or digits (0 to 9) or an underscore (_).

 all are valid example.
  An identifier cannot start with a digit.
 Keywords cannot be used as identifiers.
  Cannot use special symbols like !, @, #, $, % etc. in our identifier.
 Identifier can be of any length.
Example:
Names like myClass, var_1, and this_is_a_long_variable

Valid declarations Invalid declarations


Num Number 1
Num num 1
Num1 addition of program
_NUM 1Num NUM_temp2
Num.no IF if
Else else

STATEMENTS AND EXPRESSIONS:


Statements:
-Instructions that a Python interpreter can executes are called statements.
-A statement is a unit of code like creating a variable or displaying a value.
>>> n = 17
>>> print(n)
Here, The first line is an assignment statement that gives a value to n. The second line is a print statement
that displays the value of n.
Expressions:
-An expression is a combination of values, variables, and operators.
- A value all by itself is considered an expression, and also a variable.
- So the following are all legal expressions:
>>> 42
42
>>> a=2
>>> a+3+2
7
>>> z=("hi"+"friend")
>>> print(z)
hifriend

INPUT AND OUTPUT

INPUT: Input is data entered by user (end user) in the program. In python, input () function is available for
input.
Syntax for input() is:
variable = input (“data”)

Example:
>>> x=input("enter the name:")
enter the name: george
>>>y=int(input("enter the number"))
enter the number 3
#python accepts string as default data type. conversion is required for type.

OUTPUT: Output can be displayed to the user using Print statement .


Syntax:
print (expression/constant/variable)
Example:
>>> print
("Hello") Hello

COMMENTS:
 A hash sign (#) is the beginning of a comment.
 Anything written after # in a line is ignored by interpreter.
Eg:percentage = (minute * 100) / 60 # calculating percentage of an hour
 Python does not have multiple-line commenting feature. You have to
comment each line individually as follows :
Example:
# This is a comment.
# This is a comment, too.
# I said that already.

DOCSTRING:
  Docstring is short for documentation string.
 It is a string that occurs as the first statement in a module, function, class, or
 method definition. We must write what a function/class does in the docstring.
 Triple quotes are used while writing docstrings.
Syntax:
functionname__doc.__
Example:
def double(num):
"""Function to double the value"""
return 2*num
>>> print(double. doc ) Function to double the value

LINES AND INDENTATION:


 Most of the programming languages like C, C++, Java use braces { } to define a
 block of code. But, python uses indentation.
  Blocks of code are denoted by line indentation.
 It is a space given to the block of codes for class and function definitions or flow
control.
Example:

a=3 b=1
if a>b:
print("a is greater")
else:
print("b is greater")

QUOTATION IN PYTHON:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals. Anything that is
represented using quotations are considered as string.

single quotes (' ') Eg, 'This a string in single quotes'


double quotes (" ") Eg, "'This a string in double quotes'"
triple quotes(""" """) Eg, This is a paragraph. It is made up of multiple lines and sentences."""

TUPLE ASSIGNMENT

 An assignment to all of the elements in a tuple using a single assignment


 statement.
 Python has a very powerful tuple assignment feature that allows a tuple of
variables on the left of an assignment to be assigned values from a tuple on the
 right of the assignment.
 The left side is a tuple of variables; the right side is a tuple of values.
  Each value is assigned to its respective variable.
 All the expressions on the right side are evaluated before any of the assignments.
 This feature makes tuple assignment quite versatile.
 Naturally, the number of variables on the left and the number of values on the
 right have to be the same.
>>> (a, b, c, d) = (1, 2, 3)
ValueError: need more than 3 values to unpack

Example:
-It is useful to swap the values of two variables. With conventional assignment statements, we have to use
a temporary variable. For example, to swap a and b:

Swap two numbers Output:


a=2;b=3
print(a,b) (2, 3)
temp = a (3, 2)
a=b >>>
b = temp print(a,b)
-Tuple assignment solves this problem neatly: (a, b) = (b, a)
-One way to think of tuple assignment is as tuple packing/unpacking.
In tuple packing, the values on the left are ‘packed’ together in a tuple:

>>> b = ("George", 25, "20000") # tuple packing

-In tuple unpacking, th e va lues in a tuple on the right are ‘un pa cked’ into the variables/names on
the right:

>>> b = ("George", 25, "20000") # tuple packing >>>


(name, age, salary) = b # tuple unpacking
>>> name
'George'
>>> age
25
>>> salary
'20000'

-The right side can be any kind of sequence (string,list,tuple)


Example:
-To split an email address in to user name and a domain
>>> mailid='god@abc.org'
>>> name,domain=mailid.split('@')
>>> print name god
>>> print
(domain) abc.org

OPERATORS:
  Operators are the constructs which can manipulate the value of operands.
 Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
 called operator
 Types of Operators:
-Python language supports the following types of operators
  Arithmetic Operators
 Comparison (Relational) Operators
  Assignment Operators
  Logical Operators
 Bitwise Operators
  Membership Operators
 Identity Operators

Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction, multiplication etc. Assume,
a=10 and b=5

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand a – b = -10 operand.

* Multiplies values on either side of the operator a * b = 200


Multiplication

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand b % a = 0 and returns remainder
** Exponent Performs exponential (power) calculation on a**b =10 to the operators
power 20

// Floor Division - The division of operands where the 5//2=2 result is the quotient in
which the digits after the
decimal point are removed

Examples Output: a=10 a+b= 15 b=5


a-b= 5 print("a+b=",a+b) a*b= 50 print("a-b=",a-b) a/b= 2.0
print("a*b=",a*b) a%b= 0 print("a/b=",a/b) a//b= 2
print("a%b=",a%b) a**b= 100000 print("a//b=",a//b)
print("a**b=",a**b)

Comparison (Relational) Operators:


 Comparison operators are used to compare values.
 It either returns True or False according to the condition. Assume, a=10 and b=5

Operator Description Example

== If the values of two operands are equal, then the condition (a == b) is


becomes true. not true.

!= If values of two operands are not equal, then condition (a!=b)


is becomes true. true

> If the value of left operand is greater than the value of right (a > b) is operand,
then condition becomes true. not true.

< If the value of left operand is less than the value of right (a < b)
is operand, then condition becomes true. true.

>= If the value of left operand is greater than or equal to the (a >= b)
is value of right operand, then condition becomes true. not true.

<= If the value of left operand is less than or equal to the value (a <= b)
is of right operand, then condition becomes true. true.

Example
a=10 Output:
b=5 a>b=> True
print("a>b=>",a>b) a>b=> False print("a>b=>",a<b) a==b=> False
print("a==b=>",a==b) a!=b=> True print("a!=b=>",a!=b) a>=b=> False
print("a>=b=>",a<=b) a>=b=> True print("a>=b=>",a>=b)

Assignment Operators:
-Assignment operators are used in Python to assign values to variables.

Operator Description Example

= Assigns values from right side operands to left side c=a+b


operand
assigns value of a +b into c

+= Add AND It adds right operand to the left operand and assign c += a is the result to left
operand equivalent to c = c + a

-= Subtract It subtracts right operand from the left operand and c -= a is


AND assign the result to left operand equivalent to c = c - a

*= Multiply It multiplies right operand with the left operand and c *= a is


AND assign the result to left operand equivalent to c = c * a

/= Divide It divides left operand with the right operand and c /= a is


AND assign the result to left operand equivalent to c = c / ac
/= a is equivalent to c = c / a

%= Modulus It takes modulus using two operands and assign the c %= a is


AND result to left operand equivalent to c = c % a

**= Exponent Performs exponential (power) calculation on c **= a is


AND operators and assign value to the left operand equivalent to c = c ** a

//= Floor It performs floor division on operators and assign c //= a is


Division value to the left operand equivalent
to c = c // a

Example
a = 21 b = 10 c = 0
c=a+b
print("Line 1 - Value of c is ", c)
c += a
print("Line 2 - Value of c is ", c)
c *= a
print("Line 3 - Value of c is ", c)
c /= a
print("Line 4 - Value of c is ", c)
c =2
c %= a
print("Line 5 - Value of c is ", c) c **= a
print("Line 6 - Value of c is ", c) c //= a
print("Line 7 - Value of c is ", c)
Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
Logical Operators:
-Logical operators are the and, or, not operators.

Example Output
a = True x and y is False b = False x or y is True
print('a and b is',a and b) not x is False print('a or b is',a or b)
print('not a is',not a)

Bitwise Operators:
 A bitwise operation operates on one or more bit patterns at the level of individual
bits
Example: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Example Output
a = 60 # 60 = 0011 1100 Line 1 - Value of c is 12
b = 13 # 13 = 0000 1101 Line 2 - Value of c is 61 c = 0
Line 3 - Value of c is 49
c = a & b; # 12 = 0000 1100 Line 4 - Value of c is -61
print "Line 1 - Value of c is ", c Line 5 - Value of c is 240 c = a | b; # 61 = 0011 1101
Line 6 - Value of c is 15 print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001 print "Line 3 - Value of c is ", c
c = ~a; # -61 = 1100 0011

print "Line 4 - Value of c is ", c


c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c

Membership Operators:

 Evaluates to find a value or a variable is in the specified sequence of string, list,


 tuple, dictionary or not.
 Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operators
are used.

Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False

Identity Operators:
 They are used to check if two values (or variables) are located on the same part
 of the
memory.

Example
x=5 Output
y=5 False x2 = 'Hello' True
y2 = 'Hello' print(x1 is not y1) print(x2 is y2)

OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.

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

<> == != Equality operators

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

is is not Identity operators

in not in Membership operators

not or and Logical operators


-For mathematical operators, Python follows mathematical convention.
-The acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition, Subtraction) is a
useful way to remember the rules:
 Parentheses have the highest precedence and can be used to force an expression to evaluate in the order
you want. Since expressions in parentheses are evaluated
 first, 2 * (3-1)is 4, and (1+1)**(5-2) is 8.
  You can also use parentheses to make an expression easier to read, as in (minute
* 100) / 60, even if it doesn’t change the result.
 Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2
 *3**2 is 18, not 36.
 Multiplication and Division have higher precedence than Addition and
 Subtraction. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
 Operators with the same precedence are evaluated from left to right (except
exponentiation).

Example:
a=9-12/3+3*2-1 A=2*3+4%5-3/2+6
a=? A=6+4%5-3/2+6 find m=?
a=9-4+3*2-1 A=6+4-3/2+6 m=-43||8&&0||-2
a=9-4+6-1 A=6+4-1+6 m=-43||0||-2 a=5+6-1
A=10-1+6 m=1||-2
a=11-1 A=9+6 m=1
a=10 A=15

a=2,b=12,c=1 a=2*3+4%5-3//2+6 d=a<b>c


a=2,b=12,c=1 a=6+4-1+6 d=2<12>1 d=a<b>c-1
a=10-1+6
d=1>1 d=2<12>1-1 a=15 d=0
d=2<12>0
d=1>0
d=1

PYTHON – CONDITIONALS

 Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.
 Decision structures evaluate multiple expressions which produce TRUE or FALSE as
outcome. You need to determine which action to take and which statements to execute if outcome is TRUE
or FALSE otherwise

Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or
null, then it is assumed as FALSE value

Statement Description
if statements if statement consists of a boolean expression followed by one or more
statements
if...else statements if statement can be followed by an optional else statement, which executes
when the boolean expression is FALSE
nested if statements You can use one if or else if statement inside another if or else if
statement(s)

conditional (if)

It is similar to that of other languages. The if statement contains a logical expression using which data is
compared and a decision is made based on the result of the comparison.

Syntax

if(test-expression):
statement-block(s)
statement-x

If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if statement
is executed. If boolean expression evaluates to FALSE, then the first set of code
after the end of the if statement(s) is executed.

The simplest form is the if statement:


if x > 0:
print('x is positive')

The boolean expression after if is called the condition. If it is true, the indented statement runs. If
not, nothing happens.

if statements have the same structure as function definitions: a header followed by an indented
body. Statements like this are called compound statements.
alternative (if…else)

A second form of the if statement is “alternative execution”, in which there are two
possibilities and the condition determines which one runs.
An else statement can be combined with an if statement. An else statement contains the block of code that
executes if the conditional expression in the if statement resolves to 0 or a FALSE value.

The else statement is an optional statement and there could be at most only one else statement
following if.

Syntax

if(test-expression):
true-block-statement(s) else:

false-block-statement(s) statement-x

For example:

if x % 2 == 0:
print('x is even') else:

print('x is odd')
If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays an
appropriate message. If the condition is false, the second set of statements runs. Since the condition must
be true or false, exactly one of the alternatives will run. The alternatives are called branches, because
they are branches in the flow of execution

The elif Statement

 Sometimes there are more than two possibilities and we need more than two branches.
One way to express a computation like that is a chained conditional.
 The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon
as one of the conditions evaluates to TRUE.
 Similar to the else, the elif statement is optional. However, unlike else, for which there
can be at most one statement, there can be an arbitrary number of elif statements following an if.
 Core Python does not provide switch or case statements as in other languages, but we can use
if..elif...statements to simulate switch case

Syntax

if(test-condition-1):
statement-1 elif(test-condition-2):
statement-2
. . .
. . . elif(test-condition-n):

else:
statement-n

default-statement statement-x
For example:

if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y') else:

print('x and y are equal')

elif is an abbreviation of “else if”. Again, exactly one branch will run. There is no limit on the number of elif
statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.

if choice == 'a':
draw_a() elif choice == 'b': draw_b()
elif choice == 'c':
draw_c()

Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true,
the corresponding branch runs and the statement ends. Even if more than one condition is true, only the
first true branch runs.

NESTED CONDITIONALS (nested if...else STATEMENT)

One conditional can also be nested within another. Syntax


if(test-condition-1):
if(test-condition-2):
statement-1

else:
else:

statement-2 statement-3 statement-x

PYTHON ITERATION

Iteration - is the ability to run a block of statements repeatedly.

REASSIGNMENT

As you may have discovered, it is legal to make more than one assignment to the same variable. A
new assignment makes an existing variable refer to a new value (and stop referring to the old value).

>>> x=5

>>> x
5

>>> x=7
>>> x
7

The first time we display x, its value is 5; the second time, its value is 7.
Python uses the equal sign (=) for assignment, it is tempting to interpret a statement like a = b as a
mathematical proposition of equality; that is, the claim that a and b are equal. But this interpretation is
wrong.

First, equality is a symmetric relationship and assignment is not. For example, in mathematics,
if a=7 then 7=a. But in Python, the statement a = 7 is legal and 7 = a is not.

Also, in mathematics, a proposition of equality is either true or false for all time. If a=b now, then a will
always equal b. In Python, an assignment statement can make two variables equal, but they don’t
have to stay that way:

>>> a=5
>>> b = a # a and b are now equal
>>> a = 3 # a and b are no longer equal

>>> b
5

The third line changes the value of a but does not change the value of b, so they are no longer equal.

Reassigning variables is often useful, but you should use it with caution. If the values of variables
change frequently, it can make the code difficult to read and debug.

UPDATING VARIABLES

A common kind of reassignment is an update, where the new value of the variable depends on the old.

>>> x = x + 1

This means “get the current value of x, add one, and then update x with the new value.”
If you try to update a variable that doesn’t exist, you get an error, because Python evaluates
the right side before it assigns a value to x:

>>> x = x + 1
NameError: name 'x' is not defined

Before you can update a variable, you have to initialize it, usually with a simple assignment:

>>> x=0
>>> x=x+1

Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement.

 In general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on. There may be a situation when you need to execute a block of code
several number of times.
 Programming languages provide various control structures that allow for more complicated
execution paths.
 A loop statement allows us to execute a statement or group of statements multiple times.

Python programming language provides following types of loops to handle looping requirements

Loop Type Description


while loop Repeats a statement or group of statements while a given condition is
TRUE. It tests the condition before executing the loop body
for loop Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable
nested loops You can use one or more loop inside any another while, for loop.

While Loop

A while loop statement in Python programming language repeatedly executes a target statement as
long as a given condition is true.

Syntax

while(test-condition):
body of the loop statement-x
 Here, statement(s) may be a single statement or a block of statements.
 The condition may be any expression, and true is any non-zero value. The loop iterates while the
condition is true.
 When the condition becomes false, program control passes to the line immediately
following the loop.
 In Python, all the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as its method
of grouping statement.

Here is a version of countdown that uses a while statement:

while n > 0: print(n) n = n - 1


print('Blastoff!')

You can almost read the while statement as if it were English. It means, “While n is greater than 0, display
the value of n and then decrement n. When you get to 0, display the word Blastoff!”

More formally, here is the flow of execution for a while statement:

1. Determine whether the condition is true or false.


2. If false, exit the while statement and continue execution at the next statement.
3. If the condition is true, run the body and then go back to step 1.

This type of flow is called a loop because the third step loops back around to the top.

The body of the loop should change the value of one or more variables so that the condition becomes false
eventually and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite
loop.
In the case of countdown, we can prove that the loop terminates: if n is zero or negative, the loop never
runs. Otherwise, n gets smaller each time through the loop, so eventually we have to get to 0.

For some other loops, it is not so easy to tell. For example:

while n != 1:
print(n)
if n % 2 == 0: # n is even n = n / 2
else: # n is odd
n = n*3 + 1

The condition for this loop is n != 1, so the loop will continue until n is 1, which makes the condition false.

Each time through the loop, the program outputs the value of n and then checks whether it is even or odd.
If it is even, n is divided by 2. If it is odd, the value of n is replaced with n*3 + 1. For example, if the
argument passed to n is 3, the resulting values of n are 3, 10, 5, 16, 8, 4, 2,1.

Since n sometimes increases and sometimes decreases, there is no obvious proof that n will ever reach 1, or
that the program terminates. For some particular values of n, we can prove termination. For example, if the
starting value is a power of two, n will be even every time through the loop until it reaches 1. The previous
example ends with such a sequence, starting
with 16.

THE for STATEMENT

A for statement is also called a loop because the flow of execution runs through the body and then loops
back to the top.

Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making
errors is something that computers do well and people do poorly. In a computer program, repetition
is also called iteration.

The syntax of a for statement has a header that ends with a colon and an indented body. The body can
contain any number of statements.

Syntax

for variable in sequence:


body of the loop;
statement-x;
For example:

for i in range(4):
print('Hello!')
You should see something like this: Hello!
Hello!
Hello! Hello!

This is the simplest use of the for statement. In this case, it runs the body four times.

break STATEMENT

Sometimes you don’t know it’s time to end a loop until you get halfway through the body. In that case you
can use the break statement to jump out of the loop. break is used to break out of the innermost loop.

For example, suppose you want to take input from the user until they type done. You could write:

while True:
line = input('> ')
if line == 'done':
break print(line)
print('Done!')

The loop condition is True, which is always true, so the loop runs until it hits the break statement.

Each time through, it prompts the user with an angle bracket. If the user types done, the break
statement exits the loop. Otherwise the program echoes whatever the user types and goes back to the top
of the loop. Here’s a sample run:
>not done not done
>done
Done!

This way of writing while loops is common because you can check the condition anywhere in the loop (not
just at the top) and you can express the stop condition affirmatively (“stop when this happens”)
rather than negatively (“keep going until that happens”).

The while loop to print the squares of all the odd numbers below 10, can be modified using the break
statement, as follows

i=1
while True:
print (i * i)
i = i + 2 if(i > 10):
break

produces the output


1
9
25
49
81

continue STATEMENT

continue is used to skip execution of the rest of the loop on this iteration and continue to the end of this
iteration.

For example we wish to print the squares of all the odd numbers below 10, which are not multiples of 3,
we would modify the for loop as follows.

for n in range(1, 10, 2):


if n % 3 == 0:
continue print (n * n)

produces the output


1
25
49
pass STATEMENT

There is no limit on the number of statements that can appear in the body, but there has to be at least one.
Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven’t
written yet). In that case, you can use the pass statement, which does nothing.

if x < 0:
pass # TODO: need to handle negative values!

“pass” statement acts as a place holder for the block of code. It is equivalent to a null
operation. It literally does nothing. It can used as a place holder when the actual code
implementation for a particular block of code is not known yet but has to be filled up later.

FUNCTIONS:
 Function is a sub program which consists of set of instructions used to perform a specific task. A
large program is divided into basic building blocks called function.
Need For Function:
 When the program is too complex and large they are divided into parts. Each part is separately coded and
combined into single program. Each subprogram is called
 as function.
 Debugging, Testing and maintenance becomes easy when the program is divided
 into subprograms.
 Functions are used to avoid rewriting same code again and again in a program.
 Function provides code re-usability
 The length of the program is reduced.
Types of function:
Functions can be classified into two categories:
i) user defined function ii) Built in function
i) Built in functions
  Built in functions are the functions that are already created and stored in python.
 These built in functions are always available for usage and accessed by a
programmer. It cannot be modified.
Built in function Description

>>>max(3,4) # returns largest element


4
>>>min(3,4) # returns smallest element
3
>>>len("hello") #returns length of an object
5
>>>range(2,8,1) #returns range of given values
[2, 3, 4, 5, 6, 7]
>>>round(7.8) #returns rounded integer of the given number
8.0
>>>chr(5) #returns a character (a string) from an integer
\x05'
>>>float(5) #returns float number from string or integer
5.0
>>>int(5.0) # returns integer from string or float
5
>>>pow(3,5) #returns power of given number
243
>>>type( 5.6) #returns data type of object to which it belongs
<type 'float'>
>>>t=tuple([4,6.0,7]) # to create tuple of items from list
(4, 6.0, 7)
>>>print("good morning") # displays the given object
Good morning
>>>input("enter name: ") # reads and returns the given string enter name : George

ii)User Defined Functions:


 User defined functions are the functions that programmers create for their
 requirement and use.
 These functions can then be combined to form module which can be used in
 other programs by importing them.
  Advantages of user defined functions:
 Programmers working on large project can divide the workload by making
 different functions.
 If repeated code occurs in a program, function can be used to include those
codes and execute when needed by calling that function.
Function definition: (Sub program)
  def keyword is used to define a function.
 Give the function name after def keyword followed by parentheses in which
 arguments are given.
 End with colon (:)
  Inside the function add the program statements to be executed
 End with or without return statement

Syntax:
def fun_name(Parameter1,Parameter2…Parameter n):
statement1 statement2… statement n
return[expression]
Example:
def my_add(a,b): c=a+b return c

Function Calling: (Main Function)


 Once we have defined a function, we can call it from another function, program
 or even the Python prompt.
 To call a function we simply type the function name with appropriate
arguments.
Example:
x=5 y=4 my_add(x,y)

Flow of Execution:

 The order in which statements are executed is called the flow of execution
  Execution always begins at the first statement of the program.
  Statements are executed one at a time, in order, from top to bottom.
 Function definitions do not alter the flow of execution of the program, but
remember that statements inside the function are not executed until the function
 is called.
 Function calls are like a bypass in the flow of execution. Instead of going to the
next statement, the flow jumps to the first line of the called function, executes all the statements there, and
then comes back to pick up where it left off.
Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of
execution. This means that you will read the def statements as you are scanning from top to bottom, but
you should skip the statements of the function definition until you reach a point where that function is
called.

Function Prototypes:

i. Function without arguments and without return type ii. Function with arguments and without return
type
iii. Function without arguments and with return type
iv. Function with arguments and with return type

i) Function without arguments and without return type


o In this type no argument is passed through the function call and no output is return to main function
o The sub function will read the input values perform the operation and print the result in the same block
ii) Function with arguments and without return type
o Arguments are passed through the function call but output is not return to the main function
iii) Function without arguments and with return type
o In this type no argument is passed through the function call but output is return to the main function.
iv) Function with arguments and with return type
o In this type arguments are passed through the function call and output is return to the main function

Parameters And Arguments: Parameters:


 Parameters are the value(s) provided in the parenthesis when we write function
 header.
  These are the values required by function to work.
 If there is more than one value required, all of them will be listed in parameter
 list separated by comma.
 Example: def my_add(a,b):
Arguments :
  Arguments are the value(s) provided in function call/invoke statement.
  List of arguments should be supplied in same way as parameters are listed.
 Bounding of parameters to arguments is done 1:1, and so there should be same
 number and type of arguments as mentioned in parameter list.
 Example: my_add(x,y)
RETURN STATEMENT:
 The return statement is used to exit a function and go back to the place from
 where it was called.
 If the return statement has no arguments, then it will not return any values. But
exits from function.
Syntax:
return[expression]

Example:
def my_add(a,b):
c=a+b return c
x=5 y=4 print(my_add(x,y))
Output:
9
ARGUMENTS TYPES:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments
 Required Arguments: The number of arguments in the function call should
match exactly with the function definition. def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return my_details("george",56)

Output:
Name: george
Age 56
 Keyword Arguments:
Python interpreter is able to use the keywords provided to match the values with parameters even though
if they are arranged in out of order.

def my_details( name, age ): print("Name: ", name) print("Age ", age)
return my_details(age=56,name="george") Output:
Name: george
Age 56

 Default Arguments:
Assumes a default value if a value is not provided in the function call for that argument.
def my_details( name, age=40 ): print("Name: ", name) print("Age ", age)
return
my_details(name="george")
Output:
Name: george
Age 40

 Variable length Arguments


If we want to specify more arguments than specified while defining the function, variable length arguments
are used. It is denoted by * symbol before parameter.
def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal", ärjun")
Output:
rajan rahul micheal ärjun

MODULES:
 A module is a file containing Python definitions ,functions, statements and
 instructions.
  Standard library of Python is extended as modules.
 To use these modules in a program, programmer needs to import the
module.

 Once we import a module, we can reference or use to any of its functions or


 variables in our code.
 o There is large number of standard modules also available in python.
o Standard modules can be imported the same way as we import our user-
 defined modules.
o Every module contains many function.
o To access one of the function , you have to specify the name of the module and
the name of the function separated by dot . This format is called dot notation.
Syntax:
import module_name module_name.function_name(variable)
Importing Builtin Module: Importing User Defined Module:
import math import cal x=math.sqrt(25)
x=cal.add(5,4) print(x) print(x)

Built-in python modules are,


1.math – mathematical functions:
some of the functions in math module is,
math.ceil(x) - Return the ceiling of x, the smallest integer greater
than or equal to x
math.floor(x) - Return the floor of x, the largest integer less than or equal to x.
math.factorial(x) -Return x factorial. math.gcd(x,y)- Return the greatest common divisor of the integers a
and b
math.sqrt(x)- Return the square root of x math.log(x)- return the natural logarithm of x
math.log10(x) – returns the base-10 logarithms math.log2(x) - Return the base-2 logarithm of x.
math.sin(x) – returns sin of x radians
math.cos(x)- returns cosine of x radians
math.tan(x)-returns tangent of x radians math.pi - The mathematical constant π = 3.141592 math.e
– returns The mathematical constant e = 2.718281

2 .random-Generate pseudo-random numbers random.randrange(stop)


random.randrange(start, stop[, step])
random.uniform(a, b)
-Return a random floating point number

Program for SWAPPING(Exchanging )of Output


values
a = int(input("Enter a value ")) Enter a value 5 b = int(input("Enter b value "))
Enter b value 8 c = a a=8
a=b b=5
b = c print("a=",a,"b=",b,)

Program to find distance between two Output points


import math enter x1 7 x1=int(input("enter x1"))
enter y1 6 y1=int(input("enter y1")) enter x2 5 x2=int(input("enter x2"))
enter y2 7 y2=int(input("enter y2")) 2.5 distance =math.sqrt((x2-x1)**2)+((y2-
y1)**2)
print(distance)

Program to circulate n numbers Output:


a=list(input("enter the list")) enter the list '1234'

print(a) ['1', '2', '3', '4'] for i in range(1,len(a),1):


['2', '3', '4', '1'] print(a[i:]+a[:i]) ['3', '4', '1', '2'] ['4', '1', '2', '3']

Basic python programs:

Addition of two numbers Output a=eval(input(“enter first no”))


enter first no b=eval(input(“enter second no”)) 5
c=a+b enter second no
print(“the sum is “,c) 6
the sum is 11
Area of rectangle Output
l=eval(input(“enter the length of rectangle”)) enter the length of rectangle 5 b=eval(input(“enter
the breath of rectangle”)) enter the breath of rectangle 6 a=l*b
30
print(a)
Area & circumference of circle output r=eval(input(“enter the radius of circle”))
enter the radius of circle4 a=3.14*r*r the area of circle 50.24
c=2*3.14*r the circumference of circle print(“the area of
circle”,a) 25.12
print(“the circumference of circle”,c)
Calculate simple interest Output
p=eval(input(“enter principle amount”)) enter principle amount 5000 n=eval(input(“enter no
of years”)) enter no of years 4 r=eval(input(“enter rate of interest”))
enter rate of interest6 si=p*n*r/100 simple interest is 1200.0
print(“simple interest is”,si)

Calculate engineering cutoff Output p=eval(input(“enter physics marks”))


enter physics marks 100 c=eval(input(“enter chemistry marks”)) enter chemistry marks 99
m=eval(input(“enter maths marks”)) enter maths marks 96 cutoff=(p/4+c/4+m/2)
cutoff = 97.75
print(“cutoff =”,cutoff)

Check voting eligibility output age=eval(input(“enter ur age”))


Enter ur age If(age>=18): 19
print(“eligible for voting”) Eligible for voting else:

print(“not eligible for voting”) Find greatest of three numbers output


a=eval(input(“enter the value of a”)) enter the value of a 9 b=eval(input(“enter the value
of b”)) enter the value of a 1 c=eval(input(“enter the value of c”))
enter the value of a 8 if(a>b): the greatest no is 9
if(a>c):
print(“the greatest no is”,a)

else:
else:

print(“the greatest no is”,c) if(b>c):


print(“the greatest no is”,b) else:

print(“the greatest no is”,c)


Programs on for loop Print n natural numbers Output

for i in range(1,5,1): 1234


print(i)

Print n odd numbers Output


for i in range(1,10,2):

print(i)
13579

Print n even numbers Output


for i in range(2,10,2):

print(i)
2468
Print squares of numbers Output

for i in range(1,5,1): 1 4 9 16

print(i*i)

Print squares of numbers Output

for i in range(1,5,1): 1 8 27 64

print(i*i*i)

Programs on while loop Print n natural numbers Output i=1


1 while(i<=5): 2
print(i) 3
i=i+1 4
5
Print n odd numbers Output i=2
2 while(i<=10): 4
print(i) 6
i=i+2 8
10
Print n even numbers Output i=1
1 while(i<=10): 3
print(i) 5
i=i+2 7
9
Print n squares of numbers Output i=1
1 while(i<=5): 4
print(i*i) 9
i=i+1 16
25

Print n cubes numbers Output i=1


1 while(i<=3): 8
print(i*i*i) 27
i=i+1

find sum of n numbers Output i=1


55 sum=0
while(i<=10):
sum=sum+i i=i+1
print(sum) factorial of n numbers/product of n numbers Output i=1
3628800 product=1
while(i<=10):
product=product*i i=i+1
print(product)

sum of n numbers Output


def add(): enter a value a=eval(input(“enter a
value”)) 6 b=eval(input(“enter b value”)) enter b value
c=a+b 4
print(“the sum is”,c) the sum is 10
add()

area of rectangle using function Output


def area(): enter the length of l=eval(input(“enter the
length of rectangle”)) rectangle 20 b=eval(input(“enter the breath of rectangle”))
enter the breath of a=l*b rectangle 5
print(“the area of rectangle is”,a) the area of rectangle is
area() 100

swap two values of variables Output


def swap(): enter a value3 a=eval(input("enter a
value")) enter b value5 b=eval(input("enter b value"))
a= 5 b= 3
c=a a=b b=c
print("a=",a,"b=",b)
swap() check the no divisible by 5 or not Output
def div(): enter n value10 n=eval(input("enter n
value")) the number is divisible by if(n%5==0):
5
print("the number is divisible by 5")
else:
print("the number not divisible by 5")
div()

find reminder and quotient of given no Output


def reminder(): enter a 6 a=eval(input("enter a"))
enter b 3 b=eval(input("enter b")) the reminder is 0
R=a%b enter a 8
print("the reminder is",R) enter b 4
def quotient(): the reminder is 2.0 a=eval(input("enter a"))
b=eval(input("enter b")) Q=a/b
print("the reminder is",Q)
reminder()
quotient()

convert the temperature Output


enter temperature in def ctof(): centigrade 37
c=eval(input("enter temperature in centigrade")) the temperature in f=(1.8*c)+32
Fahrenheit is 98.6 print("the temperature in Fahrenheit is",f) enter temp in Fahrenheit
def ftoc(): 100 f=eval(input("enter temp in
Fahrenheit")) the temperature in c=(f-32)/1.8
centigrade is 37.77 print("the temperature in centigrade is",c)
ctof()
ftoc()

program for basic calculator Output


def add(): enter a value 10 a=eval(input("enter a
value")) enter b value 10 b=eval(input("enter b value"))
the sum is 20 c=a+b enter a value 10 print("the sum
is",c) enter b value 10
def sub(): the diff is 0 a=eval(input("enter a value"))
enter a value 10 b=eval(input("enter b value")) enter b value 10 c=a-b
the mul is 100 print("the diff is",c) enter a value 10
def mul(): enter b value 10
a=eval(input("enter a value")) the div is 1 b=eval(input("enter b value"))
c=a*b
print("the mul is",c)
def div():
a=eval(input("enter a value")) b=eval(input("enter b value")) c=a/b
print("the div is",c)
add() sub() mul() div()

Arrays
There is not much we can do with lists and tuples, except print them. Even when you print them,
the statements can become cumbersome. Also, there is no way to manipulate directly a list: if we
wanted to create a new list from an existing list by removing its last element, we could not. The
solution offered by Python is to store lists and tuples into arrays.
Assigning arrays
Names for arrays follow the same rules as those defined for scalar variables. We store a list into
an array the same way we store a scalar into a scalar variable, by assigning it with =:
for a tuple, or for a list.

>>> range(10)
[0,1,2,3,4,5,6,7,8,9]
>>> range(10,21)
[10,11,12,13,14,15,16,17,18,19,20]
>>> range(1,10,2)
[1,3,5,7,9]
>>> days=(‘Monday’,’Tuesday’,’Wednesday’,’Thursday’,’Friday’,’Saturday’,’Sunday’)
>>> days=[‘Monday’,’Tuesday’,’Wednesday’,’Thursday’,’Friday’,’Saturday’,’Sunday’]
Once we have assigned a list to an array, we can use it where we would use a list. For example,
will print:
[‘Monday’,’Tuesday’,’Wednesday’,’Thursday’,’Friday’,’Saturday’,’Sunday’]
Accessing one element in an array
We can access one element in an array by using the index of the drawers it has been assigned to.
Remember how we access an element in a list:
[‘Monday’,’Tuesday’,’Wednesday’,’Thursday’,’Friday’,’Saturday’,’Sunday’][0]
gives us the first element in the list, i.e. ‘Monday’. We could do:
days[0];
to access the first element of the array days.
Accessing an element in an array works both ways: we can either retrieve the value contained in
the position considered, or assign a value to that position. For example,
Scalar variables and arrays.
A scalar variable is like a single box, while an array behaves like a chest of drawers. Each of the drawers is
assigned a number, or index, which starts at 0.
>>> print days

Creates an array names numbers that contains the list [0,1,5]. This list can then be modified:
The array numbers now contains the list [3,4,5].
Important: you can change elements in a list, but you will get an error message if you try the
same thing in a tuple.
Array manipulation
Python provides a list of functions that manipulates list. Let A be a list:
Type Notation Function
Adding values A.append(obj) Adds obj at the end of list A
A.extend(list) Adds list at the end of list A
A.insert(index,item) Adds item at position index in A, and move the
remaining items to the right
Remove values del A[i] Removes element at position i in the list A
Item=A.pop(index) Removes object at position index in A, and
stores it in variable item
A.remove(item) Search for item in A, and remove first instance
Reverse A.reverse() Reverses list A
Sorting A.sort() Sorts list A in place, in increasing order
Searching I=A.index(item) Search for item in list A, and puts index of first
occurrence in i
Counting N=A.count(item) Counts the number of occurrence of item in A
Length N=len(A) Finds number of items in A, and stores in N
Important again: you can manipulate elements in a list, but you will get an error message if you
try the same thing in a tuple.
numbers = [0,1,5];
numbers[0]=3;
numbers[1]=4;
numbers[2]=5;
From arrays to string and back.
join: from array to string:
You can concatenate all elements of a list into a single string using the operator join. The syntax
is:
It concatenates all elements of LIST and stores them in the string A. Not the presence of ‘’
before join.
Split and list: from string to array
We have seen in chapter 1 that the function split will break down a string into a list, using a
specified delimiter to mark the different elements. If the delimiter is omitted, split separates each
word in the string. For example, if A=”This is a test”, A.split() will generate the list
[“This”,”is”,”a”,”test”]. Split however cannot break down a word into characters: to do that, we
use the function list.
For example, if we want to break a paragraph into sentences, a sentence into words, and a word
into characters, we use:
In all three cases, the result is a list and the input was a string
Create an Array
We can create a Python array with comma separated elements between square
brackets[].
Example 1: How to create an array in Python?
We can make an integer array and store it to arr.
arr = [10, 20, 30, 40, 50]
Access elements of an Array
We can access individual elements of an array using index inside square
brackets [].
Array Index
Index is the position of element in an array. In Python, arrays are zero-indexed. This
means, the element's position starts with 0 instead of 1.
Example 2: Accessing elements of array using indexing
arr = [10, 20, 30, 40, 50]
print(arr[0])
print(arr[1])
print(arr[2])
When we run the above program, the output will be:
10
20
30

Here, the first element of arr is arr[0], second is arr[1], third is arr[2], and so on.
Negative Indexing
Python programming supports negative indexing of arrays, something that is not
available in arrays in most programming languages.
This means the index value of -1 gives the last element, and -2 gives the second to
last element of an array.
Example 3: Accessing elements of array using negative
indexing
arr = [10, 20, 30, 40, 50]
print(arr[-1])
print(arr[-2])
When we run the above program, the output will be:
50
40
Find length of an Array
Python arrays are just lists, so finding the length of an array is equivalent to finding
length of a list in Python.
Example 4: Find length of an array using len()
brands = ["Coke", "Apple", "Google", "Microsoft", "Toyota"]
num_brands = len(brands)
print(num_brands)
When we run the above program, the output will be:

As seen from the above example, the len function gives the length of
array brands which is 5.
Add an element to an Array
To add a new element to an array, we use append() method in Python.
Example 5: Adding an element in an array using append()
add = ['a', 'b', 'c']
add.append('d')
print(add)
When we run the above program, the output will be
['a', 'b', 'c', 'd']
Here, we used append() method to add 'd'.
Remove elements from an Array
Python's list implementation of array allows us to delete any elements from an
array using del operator.
Similarly, we can also use remove() and pop() methods to remove elements in
an array.
Example 6: Removing elements of an array using del,
remove() and pop()
colors = ["violet", "indigo", "blue", "green", "yellow", "orange", "red"]
del color[4]
colors.remove("blue")
colors.pop(3)
print(color)
When we run the above program, the output will be
['violet', 'indigo', 'green', 'red']
Modify elements of an Array
We can change values of elements within an array using indexing and assignment
operator (=). We select the position of any element using indexing and use
assignment operator to provide a new value for the element.
Example 7: Modifying elements of an array using Indexing
fruits = ["Apple", "Banana", "Mango", "Grapes", "Orange"]
fruits[1] = "Pineapple"
fruits[-1] = "Guava"
print(fruits)
When we run the above program, the output will be:
['Apple', 'Pineapple', 'Mango', 'Grapes', 'Guava']
Python operators to modify elements in an Array
In Python arrays, operators like + , * can also be used to modify elements.
We can use + operator to concatenate (combine) two arrays.
Example 8: Concatenating two arrays using + operator
concat = [1, 2, 3]
concat + [4,5,6]
print(concat)
When we run the above program. the output will be:
[1, 2, 3, 4, 5, 6]
Similarly, we can use * operator to repeat the elements multiple times.
Example 8: Repeating elements in array using * operator
repeat = ["a"]
repeat = repeat * 5
print(repeat)
When we run the above program, the output will be
['a', 'a', 'a', 'a', 'a'

Slicing an Array
Python has a slicing feature which allows to access pieces of an array. We, basically,
slice an array using a given range (eg. 2nd to 5th position), giving us elements we
require. This is done by using indexes separated by a colon [x : y].
We can use negative indexing with slicing too.
Example 9: Slicing an array using Indexing
fruits = ["Apple", "Banana", "Mango", "Grapes", "Orange"]
print(fruits[1:4])
print(fruits[ : 3])
print(fruits[-4:])
print(fruits[-3:-1])
When we run the above program, the output will be:
['Banana', 'Mango', 'Grapes']
['Apple', 'Banana', 'Mango']
['Banana', 'Mango', 'Grapes', 'Orange']
['Mango', 'Grapes']
Python Array Methods
Other array operations are also available in Python using list/array methods given
as:
Methods Functions
append() to add element to the end of the list
extend() to extend all elements of a list to the another list
insert() to insert an element at the another index
remove() to remove an element from the list
pop() to remove elements return element at the given index
clear() to remove all elements from the list
index() to return the index of the first matched element
count() to count of number of elements passed as an argument
sort() to sort the elements in ascending order by default
reverse() to reverse order element in a list
copy() to return a copy of elements in a list
Multidimensional arrays
All arrays created above are single dimensional. We can also create a
multidimensional array in Python.
A multidimensional array is an array within an array. This means an array holds
different arrays inside it.
Example 10: Create a two-dimensional array using lists
multd = [[1,2], [3,4], [5,6], [7,8]]
print(multd[0])
print(multd[3])
print(multd[2][1])
print(multd[3][0])
When we run the above program, the output will be
[1, 2]
[7, 8]
6
7
Here, we have 4 elements and each elements hold another 2 sub-elements.
Basic array operations
So far so good, and it looks as if using a list is as easy as using an array.
The first thing that we tend to need to do is to scan through an array and
examine values. For example, to find the maximum value (forgetting for a
moment that there is a built-in max function) you could use:
m=0
for e in myList:
if m<e:
m=e
This uses the for..in construct to scan through each item in the list. This is a
very useful way to access the elements of an array but it isn't the one that most
programmers will be familiar with. In most cases arrays are accessed by index
and you can do this in Python:
m=0
for i in range(len(myList)):
if m<myList[i]:
m=myList[i]
or you could use the non-indexed loop and the index method:
m=0
for e in myList:
if m<e:
m=e
mi=myList.index(m)
print mi
LIST,SET,TUPLE AND DICTIONARY
A sequence is a datatype that represents a group of elements. The purpose of any sequence is to
store and process group elements. In python, strings, lists, tuples and dictionaries are very important
sequence datatypes.
LIST:
A list is similar to an array that consists of a group of elements or items. Just like an array, a list can store
elements. But, there is one major difference between an array and a list. An array can store only one
type of elements whereas a list can store different types of elements. Hence lists are more versatile
and useful than an array.
Creating a List:
Creating a list is as simple as putting different comma-separated values between square brackets.
student = [556, “Mothi”, 84, 96, 84, 75, 84 ]
We can create empty list without any elements by simply writing empty square brackets as:
student=[ ]
We can create a list by embedding the elements inside a pair of square braces []. The elements in the list
should be separated by a comma (,).
Accessing Values in list:
To access values in lists, use the square brackets for slicing along with the index or indices to obtain value
available at that index. To view the elements of a list as a whole, we can simply pass the list name to print
function.
Ex:

student = [556, “Mothi”, 84, 96, 84, 75, 84 ]


print student
print student[0] # Access 0th element
print student[0:2] # Access 0th to 1st elements
print student[2: ] # Access 2nd to end of list elements print student[ :3] # Access starting to 2nd elements
print student[ : ] # Access starting to ending elements print student[-1] # Access last index value
print student[-1:-7:-1] # Access elements in reverse order
Output:
[556, “Mothi”, 84, 96, 84, 75, 84]
Mothi
[556, “Mothi”]
[84, 96, 84, 75, 84]
[556, “Mothi”, 84]
[556, “Mothi”, 84, 96, 84, 75, 84]
84
[84, 75, 84, 96, 84, “Mothi”]

Creating lists using range() function:


We can use range() function to generate a sequence of integers which can be stored in a list. To store
numbers from 0 to 10 in a list as follows.
numbers = list( range(0,11) )
print numbers # [0,1,2,3,4,5,6,7,8,9,10]
To store even numbers from 0 to 10in a list as follows. numbers = list( range(0,11,2) )
print numbers # [0,2,4,6,8,10]
Looping on lists:
We can also display list by using for loop (or) while loop. The len( ) function useful to know the numbers of
elements in the list. while loop retrieves starting from 0th to the last element i.e. n-1

Ex-1:
numbers = [1,2,3,4,5]
for i in numbers:
print i,

Output:
12345

Updating and deleting lists:


Lists are mutable. It means we can modify the contents of a list. We can append, update or delete the
elements of a list depending upon our requirements.
Appending an element means adding an element at the end of the list. To, append a new element to the
list, we should use the append() method.
Example:
lst=[1,2,4,5,8,6]
print lst # [1,2,4,5,8,6]
lst.append(9)
print lst # [1,2,4,5,8,6,9]
Updating an element means changing the value of the element in the list. This can be done by accessing the
specific element using indexing or slicing and assigning a new value.
Example:
lst=[4,7,6,8,9,3]
print lst # [4,7,6,8,9,3]
lst[2]=5 # updates 2nd element in the list print lst # [4,7,5,8,9,3]
lst[2:5]=10,11,12 # update 2nd element to 4th element in the list
print lst # [4,7,10,11,12,3]

Deleting an element from the list can be done using ‘del’ statement. The del statement takes the position
number of the element to be deleted.
Example:
lst=[5,7,1,8,9,6]
del lst[3] # delete 3rd element from the list i.e., 8 print lst # [5,7,1,9,6]
If we want to delete entire list, we can give statement like del lst.
Concatenation of Two lists:
We can simply use „+‟ operator on two lists to join them. For example, „x‟ and „y‟ are two lists. If we wrte
x+y, the list „y‟ is joined at the end of the list „x‟.
Example: x=[10,20,32,15,16] y=[45,18,78,14,86]
print x+y # [10,20,32,15,16,45,18,78,14,86]
Repetition of Lists:
We can repeat the elements of a list „n‟ number of times using „*‟
operator. x=[10,54,87,96,45]
print x*2 # [10,54,87,96,45,10,54,87,96,45]
Membership in Lists:
We can check if an element is a member of a list by using „in‟ and „not in‟ operator. If the element is a
member of the list, then „in‟ operator returns True otherwise returns False. If the element is not in the list,
then „not in‟ operator returns True otherwise returns False.
Example: x=[10,20,30,45,55,65] a=20
print a in x # True a=25
print a in x # False a=45
print a not in x # False a=40
print a not in x # True
Aliasing and Cloning Lists:
Giving a new name to an existing list is called ‘aliasing’. The new name is called
‘alias name’. To provide a new name to this list, we can simply use assignment operator (=).
Example:
x = [10, 20, 30, 40, 50, 60]
y=x # x is aliased as y print x # [10,20,30,40,50,60] print y # [10,20,30,40,50,60]
x[1]=90 # modify 1st element in x print x # [10,90,30,40,50,60] print y #
[10,90,30,40,50,60]

In this case we are having only one list of elements but with two different names „x‟ and „y‟. Here, „x‟ is the
original name and „y‟ is the alias name for the same list. Hence, any modifications done to x‟ will also modify
„y‟ and vice versa.
Obtaining exact copy of an existing object (or list) is called „cloning‟. To Clone a list, we can take help of the
slicing operation [:].
Example:
x = [10, 20, 30, 40, 50, 60]
y=x[:] # x is cloned as y
print x # [10,20,30,40,50,60] print y # [10,20,30,40,50,60] x[1]=90 # modify 1 st element
in x print x # [10,90,30,40,50,60] print y # [10,20,30,40,50,60]

When we clone a list like this, a separate copy of all the elements is stored into „y‟. The lists „x‟ and „y‟ are
independent lists. Hence, any modifications to „x‟ will not affect „y‟and vice versa.

Methods in Lists:

Method Description lst.index(x) Returns the first occurrence of x in the


list. lst.append(x) Appends x at the end of the list.
lst.insert(i,x) Inserts x to the list in the position specified by i. lst.copy() Copies all the list
elements into a new list and returns it. lst.extend(lst2) Appends lst2 to list.
lst.count(x) Returns number of occurrences of x in the list.
lst.remove(x) Removes x from the list.
lst.pop() Removes the ending element from the list. lst.sort() Sorts the elements of
list into ascending order. lst.reverse() Reverses the sequence of elements in the list. lst.clear()
Deletes all elements from the list.
max(lst) Returns biggest element in the list.
min(lst) Returns smallest element in the list.

Example: lst=[10,25,45,51,45,51,21,65] lst.insert(1,46)


print lst # [10,46,25,45,51,45,51,21,65]
print lst.count(45) #2

Finding Common Elements in Lists:


Sometimes, it is useful to know which elements are repeated in two lists. For example, there is a
scholarship for which a group of students enrolled in a college. There is another scholarship for which
another group of students got enrolled. Now, we wan to know the names of the students who enrolled for
both the scholarships so that we can restrict them to take only one scholarship. That means, we are
supposed to find out the common students (or elements) both the lists.
First of all, we should convert the lists into lists into sets, using set( ) function, as: set(list). Then we
should find the common elements in the two sets using intersection() method.
Example:
scholar1=[ „mothi‟, „sudheer‟, „vinay‟, „narendra‟, „ramakoteswararao‟
]scholar2=[ „vinay‟, „narendra‟, „ramesh‟]
s1=set(scholar1) s2=set(scholar2) s3=s1.intersection(s2) common =list(s3)
print common # display [ „vinay‟, „narendra‟ ]

Nested Lists:
A list within another list is called a nested list. We know that a list contains several elements. When we take
a list as an element in another list, then that list is called a nested list.
Example: a=[10,20,30] b=[45,65,a]
print b # display [ 45, 65, [ 10, 20, 30 ] ]
print b[1] # display 65
print b[2] # display [ 10, 20, 30 ]
print b[2][0] # display 10 print b[2][1] # display 20 print b[2][2] # display 30 for x in b[2]:
print x, # display 10 20 30

Nested Lists as Matrices:


Suppose we want to create a matrix with 3 rows 3 columns, we should create a list with 3 other lists as:
mat = [ [ 1, 2, 3 ] , [ 4, 5, 6 ] , [ 7, 8, 9 ] ]
Here, „mat‟ is a list that contains 3 lists which are rows of the „mat‟ list. Each row contains again 3
elements as:
[ [ 1, 2, 3] , # first row
[ 4, 5, 6] , # second row
[ 7, 8, 9] ] # third row
Example:

mat=[[1,2,3],[4,5,6],[7,8,9]]
for r in mat:
print r print "" m=len(mat) n=len(mat[0])
for i in range(0,m):
for j in range(0,n):
print mat[i][j], print ""
print ""

One of the main use of nested lists is that they can be used to represent matrices. A matrix represents a
group of elements arranged in several rows and columns. In python, matrices are created as 2D
arrays or using matrix object in numpy. We can also create a matrix using nested lists.

Q) Write a program to perform addition of two matrices. a=[[1,2,3],[4,5,6],[7,8,9]] b=[[4,5,6],[7,8,9],[1,2,3]]


c=[[0,0,0],[0,0,0],[0,0,0]]
m1=len(a) n1=len(a[0]) m2=len(b) n2=len(b[0])
for i in range(0,m1):
for j in range(0,n1):
c[i][j]= a[i][j]+b[i][j]
for i in range(0,m1):
for j in range(0,n1):
print "\t",c[i][j], print ""

Q) Write a program to perform multiplication of two matrices. a=[[1,2,3],[4,5,6]]


b=[[4,5],[7,8],[1,2]]
c=[[0,0],[0,0]] m1=len(a) n1=len(a[0]) m2=len(b) n2=len(b[0])
for i in range(0,m1):
for j in range(0,n2):
for k in range(0,n1):
c[i][j] += a[i][k]*b[k][j]
for i in range(0,m1):
for j in range(0,n2):
print "\t",c[i][j], print ""

List Comprehensions:
List comprehensions represent creation of new lists from an iterable object (like a list, set, tuple, dictionary
or range) that satisfy a given condition. List comprehensions contain very compact code usually a single
statement that performs the task.
We want to create a list with squares of integers from 1 to 100. We can write code as:
squares=[ ]
for i in range(1,11):
squares.append(i**2)
The preceding code will create „squares‟ list with the elements as shown below:
[ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ] The previous code can rewritten in a
compact way as:
squares=[x**2 for x in range(1,11)]
This is called list comprehension. From this, we can understand that a list comprehension
consists of square braces containing an expression (i.e., x**2). After the expression, a fro loop and
then zero or more if statements can be written.
[ expression for item1 in iterable if statement1 for item1 in iterable if statement2
for item1 in iterable if statement3 …..]

Example:
Even_squares = [ x**2 for x
in range(1,11) if x%2==0 ] It will display the list even
squares as list.
[ 4, 16, 36, 64, 100 ]

TUPLE:
A Tuple is a python sequence which stores a group of elements or items. Tuples are similar to lists but the
main difference is tuples are immutable whereas lists are mutable. Once we create a tuple we cannot
modify its elements. Hence, we cannot perform operations like append(), extend(), insert(), remove(), pop()
and clear() on tuples. Tuples are generally used to store data which should not be modified and retrieve
that data on demand.
Creating Tuples:
We can create a tuple by writing elements separated by commas inside parentheses( ). The elements can be
same datatype or different types.
To create an empty tuple, we can simply write empty parenthesis, as:
tup=( )
To create a tuple with only one element, we can, mention that element in parenthesis and after that a
comma is needed. In the absence of comma, python treats the element assign ordinary data type.
tup = (10) tup = (10,)
print tup # display 10 print tup # display 10
print type(tup) # display <type „int‟> print type(tup) # display<type„tuple‟>
To create a tuple with different types of elements:
tup=(10, 20, 31.5, „Gudivada‟)
If we do not mention any brackets and write the elements separating them by comma, then they are taken
by default as a tuple.
tup= 10, 20, 34, 47
It is possible to create a tuple from a list. This is done by converting a list into a tuple using tuple function.
n=[1,2,3,4]
tp=tuple(n)
print tp # display (1,2,3,4)
Another way to create a tuple by using range( ) function that returns a sequence. t=tuple(range(2,11,2))
print t # display (2,4,6,8,10)
Accessing the tuple elements:
Accessing the elements from a tuple can be done using indexing or slicing. This is same as that of a list.
Indexing represents the position number of the element in the tuple. The position starts from 0.
tup=(50,60,70,80,90)
print tup[0] # display 50
print tup[1:4] # display (60,70,80)
print tup[-1] # display 90
print tup[-1:-4:-1] # display (90,80,70)
print tup[-4:-1] # display (60,70,80)

Updating and deleting elements:


Tuples are immutable which means you cannot update, change or delete the values of tuple elements.

However, you can always delete the entire tuple by using the statement.

Note that this exception is raised because you are trying print the deleted element.

Operations on tuple:
Operation Description len(t) Return the length of tuple. tup1+tup2
Concatenation of two tuples.
Tup*n Repetition of tuple values in n number of times.
x in tup Return True if x is found in tuple otherwise returns False. cmp(tup1,tup2) Compare
elements of both tuples
max(tup) Returns the maximum value in tuple. min(tup) Returns the minimum value in
tuple. tuple(list) Convert list into tuple.
Returns how many times the element „x‟ is found in tuple.
tup.count(x)
Returns the first occurrence of the element „x‟ in tuple.
tup.index(x)
Raises ValueError if „x‟ is not found in the tuple.

Sorts the elements of tuple into ascending order. sorted(tup,reverse=True) will sort in
sorted(tup)
reverse order.
cmp(tuple1, tuple2)
The method cmp() compares elements of two tuples.
Syntax
cmp(tuple1, tuple2)
Parameters
tuple1 -- This is the first tuple to be compared
tuple2 -- This is the second tuple to be compared
Return Value
If elements are of the same type, perform the compare and return the result. If elements are different
types, check to see if they are numbers.
➢ If numbers, perform numeric coercion if necessary and compare.
➢ If either element is a number, then the other element is "larger" (numbers are
"smallest").
➢ Otherwise, types are sorted alphabetically by name.
If we reached the end of one of the tuples, the longer tuple is "larger." If we exhaust both tuples and share
the same data, the result is a tie, meaning that 0 is returned.
Example:
tuple1 = (123, 'xyz')
tuple2 = (456, 'abc') print cmp(tuple1, tuple2)
print cmp(tuple2, tuple1)

Nested Tuples:
#display -1
#display 1 Python allows you to define a tuple inside another tuple. This is called a nested tuple.
students=((“RAVI”, “CSE”, 92.00), (“RAMU”, “ECE”, 93.00), (“RAJA”, “EEE”, 87.00))
for i in students:
print i
Output: (“RAVI”, “CSE”, 92.00) (“RAMU”, “ECE”, 93.00) (“RAJA”, “EEE”, 87.00)

SET:
Set is another data structure supported by python. Basically, sets are same as lists but with a difference
that sets are lists with no duplicate entries. Technically a set is a mutable and an unordered collection of
items. This means that we can easily add or remove items from it.
Creating a Set:
A set is created by placing all the elements inside curly brackets {}. Separated by comma or by using the
built-in function set( ).
Syntax:
Set_variable_name={var1, var2, var3, var4, …….}
Example:
s={1, 2.5, “abc” }
print s # display set( [ 1, 2.5, “abc” ] )
Converting a list into set:
A set can have any number of items and they may be of different data types. set()
function is used to converting list into set.
s=set( [ 1, 2.5, “abc” ] )
print s # display set( [ 1, 2.5, “abc” ] ) We can also convert tuple or string into set.
tup= ( 1, 2, 3, 4, 5 )
print set(tup) # set( [ 1, 2, 3, 4, 5 ] )
str= “MOTHILAL”
print str # set( [ 'i', 'h', 'm', 't', 'o' ] )

Operations on set:
Sno Operation Result
1 len(s) number of elements in set s (cardinality)
2 x in s test x for membership in s
3 x not in s test x for non-membership in s
s.issubset(t) 4 (or)
s <= t s.issuperset(t)
5 (or)
s >= t

6 s==t

7 s ! = t s.union(t)
8 (or)
s|t s.intersection(t)
9 (or)
s&t
test whether every element in s is in t

test whether every element in t is in s

Returns True if two sets are equivalent and returns


False.
Returns True if two sets are not equivalent and returns False.

new set with elements from both s and t

new set with elements common to s and t

Sno Operation Result


s.difference(t) 10 (or) s-t s.symmetric_difference(t)
11 (or)
s^t

new set with elements in s but not in t

new set with elements in either s or t but not both 12 s.copy() new set with a shallow copy of s
13 s.update(t) return set s with elements added from t
14 s.intersection_update(t) return set s keeping only elements also found in t
15 s.difference_update(t) return set s after removing elements found in t
s.symmetric_difference_up
16 return set s with elements from s or t but not both
date(t)
17 s.add(x) add element x to set s
18 s.remove(x) remove x from set s; raises KeyError if not present
19 s.discard(x) removes x from set s if present
remove and return an arbitrary element from s; 20 s.pop()
raises KeyError if empty 21 s.clear() remove all elements from set s
22 max(s) Returns Maximum value in a set
23 min(s) Returns Minimum value in a set
Return a new sorted list from the elements in the 24 sorted(s)
set.

To create an empty set you cannot write s={}, because python will make this as a directory. Therefore, to
create an empty set use set( ) function. s=set( ) s={}
print type(s) #display<type„set‟> print type(s) # display <type„dict‟>
Updating a set:
Since sets are unordered, indexing has no meaning. Set operations do not allow users to access or change
an element using indexing or slicing.

Dictionary:
A dictionary represents a group of elements arranged in the form of key-value pairs. The first element is
considered as „key‟ and the immediate next element is taken as its
„value‟. The key and its value are separated by a colon (:). All the key-value pairs in a dictionary are inserted
in curly braces { }.
d= { „Regd.No‟: 556, „Name‟:‟Mothi‟, „Branch‟: „CSE‟ }
Here, the name of dictionary is „dict‟. The first element in the dictionary is a string
„Regd.No‟. So, this is called „key‟. The second element is 556 which is taken as its „value‟.
Example:
d={„Regd.No‟:556,„Name‟:‟Mothi‟,„Branch‟:„CSE‟}print
d[„Regd.No‟] # 556 print d[„Name‟] # Mothi print d[„Branch‟] # CSE
To access the elements of a dictionary, we should not use indexing or slicing. For example,
dict[0] or dict[1:3] etc. expressions will give error. To access the value associated with a key,
we can mention the key name inside the square braces, as: dict[„Name‟].
If we want to know how many key-value pairs are there in a dictionary, we can use the len( )
function, as shown
d={„Regd.No‟:556,„Name‟:‟Mothi‟,„Branch‟:„CSE‟ } print len(d) #3
We can also insert a new key-value pair into an existing dictionary. This is done by mentioning the key and
assigning a value to it.
d={'Regd.No':556,'Name':'Mothi','Branch':'CSE'}
print d #{'Branch': 'CSE', 'Name': 'Mothi', 'Regd.No': 556}
d['Gender']="Male"
print d # {'Gender': 'Male', 'Branch': 'CSE', 'Name': 'Mothi', 'Regd.No': 556} Suppose, we want to delete a
key-value pair from the dictionary, we can use del statement as:
del dict[„Regd.No‟] #{'Gender': 'Male', 'Branch': 'CSE', 'Name': 'Mothi'}
To Test whether a „key‟ is available in a dictionary or not, we can use „in‟ and „not in‟
operators. These operators return either True or False.
„Name‟ in d # check if „Name‟ is a key in d and returns True / False
We can use any datatypes for value. For example, a value can be a number, string, list, tuple or another
dictionary. But keys should obey the rules:
➢ Keys should be unique. It means, duplicate keys are not allowd. If we enter same key again, the old key
will be overwritten and only the new key will be available.
emp={'nag':10,'vishnu':20,'nag':20}
print emp # {'nag': 20, 'vishnu': 20}
➢ Keys should be immutable type. For example, we can use a number, string or tuples as keys since they
are immutable. We cannot use lists or dictionaries as keys. If they are used as keys, we will get „TypeError‟.
emp={['nag']:10,'vishnu':20,'nag':20} Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
emp={['nag']:10,'vishnu':20,'nag':20} TypeError: unhashable type: 'list'

Dictionary Methods:
Method Description
d.clear() Removes all key-value pairs from dictionary„d‟.
d2=d.copy() Copies all elements from„d‟ into a new dictionary d2.
Created.fromkeys(s
a new dictionary with
[,v]keys)from sequence„s‟ and values all set to „v‟.
Returns the value associated
d.get(k [,v] ) with key „k‟. If key is not found, it returns „v‟.
Returns an object that contains key-value pairs of„d‟. The
pairs are stored as tuples in the object.
d.items()
d.keys() Returns a sequence of keys from the dictionary„d‟. d.values() Returns a sequence of
values from the dictionary„d‟. d.update(x) Adds all elements from dictionary „x‟ to„d‟.
Removes the key „k‟ and its value from„d‟ and returns the
d.pop(k [,v] )
value. If key is not found, then the value „v‟ is returned. If key is not found and „v‟ is not mentioned then
„KeyError‟ is raised. If key „k‟ is found, its value is returned. If key is not found, then the k, v pair is stored into
d.setdefault(k [,v] )
the dictionary„d‟.
Using for loop with Dictionaries:
for loop is very convenient to retrieve the elements of a dictionary. Let‟s take a simple dictionary that
contains color code and its name as:
colors = { 'r':"RED", 'g':"GREEN", 'b':"BLUE", 'w':"WHITE" }
Here, „r‟, „g‟, „b‟ represents keys and „RED‟, „GREEN‟, „BLUE‟ and „WHITE‟
indicate values.
colors = { 'r':"RED", 'g':"GREEN", 'b':"BLUE", 'w':"WHITE" }
for k in colors:
print k # displays only keys for k in colors:
print colors[k] # keys to to dictionary and display the values

Converting Lists into Dictionary:

When we have two lists, it is possible to convert them into a dictionary. For example, we have two lists
containing names of countries and names of their capital cities.
There are two steps involved to convert the lists into a dictionary. The first step is to create a „zip‟ class
object by passing the two lists to zip( ) function. The zip( ) function is useful to convert the sequences into a
zip class object. The second step is to convert the zip object into a dictionary by using dict( ) function.
Example:
countries = [ 'USA', 'INDIA', 'GERMANY', 'FRANCE' ] cities = [ 'Washington', 'New Delhi', 'Berlin', 'Paris' ]
z=zip(countries, cities)
d=dict(z)
print d

Output:
{'GERMANY': 'Berlin', 'INDIA': 'New Delhi', 'USA': 'Washington', 'FRANCE': 'Paris'}

Converting Strings into Dictionary:


When a string is given with key and value pairs separated by some delimiter like a comma ( , ) we can
convert the string into a dictionary and use it as dictionary.
s="Vijay=23,Ganesh=20,Lakshmi=19,Nikhil=22" s1=s.split(',')
s2=[]
d={}
for i in s1:
s2.append(i.split('='))
print d

{'Ganesh': '20', 'Lakshmi': '19', 'Nikhil': '22', 'Vijay': '23'}


Q) A Python program to create a dictionary and find the sum of values.
d={'m1':85,'m3':84,'eng':86,'c':91}
sum=0
for i in d.values():
sum+=i
print sum # 346

Q) A Python program to create a dictionary with cricket player’s names and scores in a match. Also we are
retrieving runs by entering the player’s name.
n=input("Enter How many players? ")
d={}
for i in range(0,n):
k=input("Enter Player name: ")
v=input("Enter score: ")
d[k]=v print d
name=input("Enter name of player for score: ")
print "The Score is",d[name]

Enter How many players? 3


Enter Player name: "Sachin" Enter score: 98
Enter Player name: "Sehwag" Enter score: 91
Enter Player name: "Dhoni" Enter score: 95
{'Sehwag': 91, 'Sachin': 98, 'Dhoni': 95} Enter name of player for score: "Sehwag" The Score is 91

Python Turtle
Turtle Drawing
We can create cool images and graphics in Python using a module called turtle - a set of
ready-made functions designed for drawing shapes and lines.
A turtle is like a cursor that moves around your screen, leaving a line behind it. Turtles can draw
all kinds of shapes and pictures - you just need to give them the right commands.

Drawing a Circle
Firstly, we are going to draw a simple shape (a circle) using the turtle module.
● Import the turtle module.
import turtle
● Make a turtle and load it into a variable.
tina = turtle.Turtle()
We have named the turtle Tina, however, you can give the turtle any name you want.
● Set the colour that the turtle will use to draw the shape.
tina.color(‘blue’)
● Set the style of the turtle with a function called shape.
tina.shape(‘turtle’)
● Set the turtle’s speed, choosing a number between 1 and 100 (100 is the fastest).
tina.speed(10)
● Set the thickness of the line your turtle will draw.
tina.pensize(4)
● Now, tell your turtle to draw a circle.
tina.circle(60) # draws circle with radius of 60 pixels

Tasks:
1. Run the code above.
2. Fill the inside of the circle with a colour (same colour as the outline).
tina.fillcolor('blue')
tina.begin_fill()
tina.circle(60)
tina.end_fill()
3. Fill the inside of the circle with a different colour (different colour as the outline).

Drawing Location
Sometimes we may wish to move the turtle before we start drawing something so we can draw
shapes in different locations on the screen.
● Set up Tina the Turtle.
● Take the pen up off the page so Tina does not draw lines while moving to a different
location.
tina.penup()
● Tell Tina to go to a particular point on the screen by telling her the x-coordinate and the
y-coordinate.
tina.goto(30,-150) # x, y
Note: The screen has coordinates that go from -150 to 150 in the x (horizontal) and y
(vertical) directions.

Python Turtle
● Put the pen back down on the screen so Tina can start drawing.
tina.pendown()
● Start drawing your shape!
tina.circle(50)

Olympic Flag Project


The Olympic Council of Ireland have asked you to draw the Olympic flag so they can use it on
their new website.
Use what you have learned in this lesson to write code to make Tina the Turtle draw the
Olympic flag. You will find an image of this below, to help you.

Drawing a Square
We can also draw shapes other than circles. Although, they are a little bit more complicated to
draw. In order to draw other shapes, Tina must draw straight lines and then turn a certain
number of degrees and then repeat.
We are now going to draw a square using Tina the Turtle.
● Set up Tina like we did in the last lesson (import module, make turtle, set color, set
speed etc.).
● Now, tell Tina where to draw.
tina.forward(50) # go right 50 pixels
tina.right(90) # turn right 90 degrees
tina.forward(50) # go down 50 pixels
tina.right(90) # turn right 90 degrees
tina.forward(50) # go left 50 pixels
tina.right(90) # turn right 90 degrees
tina.forward(50) # go up 50 pixels
Tasks:
1. Run the code above.
2. Fill the square with a colour.

Drawing Other Shapes


In order to draw any shape, we must know three things:
● How many lines there are.
● How long each line will be.
● The angle that Tina must turn after each line has been drawn.
The only one from that list that may be difficult to know is the last one. So here’s a guide to help
you calculate the angle that Tina must turn to draw the shape that you want!
To calculate the amount of degrees you must turn to draw a certain shape, use the
following formula:
Number of degrees = 360 Number of sides in shape÷
Let’s take a triangle for example. A triangle is a three-sided shape. So let’s fill that into our
formula.
Number of degrees = 360 3 = 120÷
Hint: use a calculator to do the maths if you can’t do it in your head!
So the code to draw a triangle would look something like this:
tina.forward(50)
tina.right(120)
tina.forward(50)
tina.right(120)
tina.forward(50)
Tasks:
1. Write code to make Tina draw a pentagon (5 sides)
2. Write code to make Tina draw an octagon (8 sides)

Writing with Turtles


Other than drawing lines and shapes, Tina the Turtle can also write words and sentences onto
the canvas.
We are now going to write something onto the canvas using Tina the Turtle.
● Set up Tina the Turtle (import module, make turtle, set color, set speed etc.).
● Tell Tina what to write on the canvas.
tina.write('Hello World!')
● You can change the font and font size of what Tina is writing.
tina.write('Hello World!', font=('Arial', 12, 'normal'))
Tasks:
1. Run the code above.
2. Change the color of the font.
3. Change the font size.

Python with Turtle

Python with Turtle is a Python library that enables


you to create virtual drawings and shapes. The
“turtle” is a the pen that you use to draw.

- Part of the original Logo programming language developed by


Wally Feurzig and Seymour Papert in 1966
- Turtles are a type of educational robots designed in the 1940s, that are typically
designed low to the ground. Some turtles are specifically designed to have pens
attached to the back of them so they can draw on large sheets of paper.
- It uses tkinter for the underlying graphics, it needs a version of
Python installed with Tk support.

A Basic Program on Turtle


● There is no programming language called ‘turtle’, so we use Python whenever we import the turtle
library. Because of this, on our first line of code, we need to tell our computer we are using turtle:

>> import turtle

● Next, we need to name our turtle, and turtle will respond to whatever name you give it.
We are just going to name it “alfred”.

>> alfred = turtle.Turtle()

● After that, we can make alfred move forward, and we can do this by using the forward
command in turtle. Whatever number you put in the parentheses is how many pixels alfred
will move forward.

>> alfred.forward(40)
● Similarly, we can have alfred move backwards.

>> alfred.backward(40)

● We can also increase the speed of alfred by using the following command:

>> alfred.speed(100)

● Now, we want to be able to control alfred with the arrow keys, so we


will put down the following function to allow the screen to follow
certain commands.

screen
>> = turtle.Screen()

● Next, we need to create functions that are going to be in charge of alfred moving up, down,
left, and right.

>> def moveUp(): alfred.setheading(90) alfred.forward(50)


>>def moveDown(): alfred.setheading(-90) alfred.forward(50)
>> def moveRight(): alfred.setheading(0) alfred.forward(50)
>> def moveLeft(): alfred.setheading(180) alfred.forward(50)

● Now we need to make alfred move in each direction when the corresponding key is
pressed, we can do this by using the following commands that call the functions we made
earlier:

>>screen.onkey(moveUp ,”Up”)

>>screen.onkey(moveDown, ”Down”)

>>screen.onkey(moveRight ,”Right”)

>>screen.onkey(moveLeft, ”Left”)

● Next, we need to make the Screen listen to the commands we are giving it
>>screen.listen()

Turtle Functions
- turtle.Turtle()
- Makes a Turtle
- turtle.Screen()
- Makes a Screen
- .forward(int)
- Moves Turtle Forward
- .backward(int)
- Moves Turtle Backward
- .left(int)
- Turns Turtle Left
- .right(int)
- Turns Turtle Right

- .color(string or int,int,int).
- Changes Turtle Color
- .penup().
- Enables the turtle to move around without drawing
- .pendown().
- Enables drawing
- .pensize(int)
- Changes Turtle Size
- .speed(int)
- Changes Turtle Speed
- .shape(string).
- Changes Turtle Shape

- .fillcolor(string)
- Sets to fill in something drawn by the turtle with a color
- .begin_fill().
- Starting spot for filling color
- .end_fill().
- Ending spot for filling color
- .xcor()
- Find X coordinate of Turtle
- .ycor()
- Find Y coordinate of Turtle

- .goto(int, int).
- Moves Turtle to a specific Spot
- .circle(int)
- Draws a Circle
- .setheading(int)
- Set orientation of the
Turtle
- .home().
- Send Turtle to 0, 0 and makes it go back to its starting orientation
- .undo().
- Undo the Turtle last actions

- .position()
- Returns Turtle’s position
- .towards(int, int)
- Returns the angle from the Turtle’s position to the position given
- .heading()
- Returns Turtle’s current heading
- .distance(int, int or turtle).
- Returns distance between turtle and given point or anothers turtle
- .degrees(int)
- Set Number of Degrees for a Full Circle
- .radians()
- Set Angle Measurement Units to Radians
- .isdown()
- Check to see if Pen is
Down or Up
- .reset().
- Delete All of Turtle’s Drawings, re-center Turtle, put everything back to default

You might also like