Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Python Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Python Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

TALENTHOME SOLUTIONS

Contents
What is python?.....................................................................................................................................0
Python Execution Model.......................................................................................................................1
Opening IDLE – The Default IDE.........................................................................................................1
Identifier................................................................................................................................................2
Operators & Operands...........................................................................................................................3
Input and Output in Python....................................................................................................................6
Conditional Statements..........................................................................................................................9
 Programs on Conditional Statements:..................................................................................12
 Iterative Statements.............................................................................................................15
 Programs on Iterative Statements:.......................................................................................17
Indentation...........................................................................................................................................23
Structured / Sequence Data Types.......................................................................................................24
 5.1....................................................................................................................................Lists
............................................................................................................................................24
 5.2.................................................................................................................................Tuples
............................................................................................................................................29
 5.3.........................................................................................................................Dictionaries
............................................................................................................................................31

hp 0
TALENTHOME SOLUTIONS

What is python?
 Python is a general-purpose, interpreted, interactive, object-oriented, and high-level
programming language
 It is a scripting language.
 Python is designed to be highly readable.
 It uses English keywords frequently where as other languages use punctuation, and it
has fewer syntactical constructions than other languages.
 Python is a powerful modern computer programming language.
 Python allows you to use variables without declaring them (i.e., it determines types
implicitly), and it relies on indentation as a control structure.
 You are not forced to define classes in Python (unlike Java) but you are free to do so
when convenient.
 Invented in the Netherlands, early 90s by Guido van Rossum at the National Research
Institute for Mathematics and Computer Science
 Named after Monty Python
 Free and open sourced from the beginning
 But Python is also free in other important ways, for example you are free to copy it as
many times as you like, and free to study the source code, and make changes to it.
 Python is a good choice for mathematical calculations, since we can write code
quickly, test it easily, and its syntax is similar to the way mathematical ideas are
expressed in the mathematical literature. (majorly used for Data Analysis &
Machine Learning)

Features of Python:
 Interpreted
 Interactive
 Object oriented
 Beginner’s Language

Python Execution Model

 Python is considered an interpreted language because Python programs are executed


by an interpreter.
 An interpreter reads a high-level program and executes it, meaning that it does what
the program says. It processes the program a little at a time, alternately reading lines
and performing computations.

hp 1
TALENTHOME SOLUTIONS

 There are two ways to use the interpreter: interactive mode and script mode.
 In interactive mode, you type Python programs and the interpreter displays the result:
 >>> 1 + 1
2
 Alternatively, you can store code in a file and use the interpreter to execute the
contents of the file, which is called a script. By convention, Python scripts have names
that end with .py.

Opening IDLE – The Default IDE


 Go to the start menu
 Find python
 Run the program labelled IDLE (Integrated Development Environment)
 The easiest way to get started is to run Python as an interpreter, which behaves similar
to the way one would use a calculator.
 In the interpreter, you type a command, and Python produces the answer.
 Then you type another command, which again produces an answer, and so on.

Standard Data Types


The data stored in memory can be of many types. For example, a person's age is stored as a
numeric value and his or her address is stored as alphanumeric characters. Python has various
standard data types that are used to define the operations possible on them and the storage
method for each of them.

Python has five standard data types −


 Numeric: Int and Float
o Int:
Number data types store numeric values like 1,20,-35,0. Number objects are
created when you assign a value to them. For example −
var1 = 1
var2 = 10

o Float
Float means decimal numbers like 2.5, 0.185, 35.36971

 String
Strings are contiguous set of characters represented in the quotation marks. Python
allows for either pairs of single or double quotes. Example –
Str = “Hello World”
Str = ‘Python’

 List
Lists are the most versatile of Python's compound data types. A list contains items
separated by commas and enclosed within square brackets ([]). To some extent, lists
are similar to arrays in C. One difference between them is that all the items belonging
to a list can be of different data type. Example -
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

hp 2
TALENTHOME SOLUTIONS

tinylist = [123, 'john']


 Tuple
A tuple is another sequence data type that is similar to the list. A tuple consists of a
number of values separated by commas. Unlike lists, however, tuples are enclosed
within parentheses (). Example-
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')

 Dictionary
Dictionary element has 2 parts: key and value. A dictionary key can be almost any
Python type, but are usually numbers or strings. Values, on the other hand, can be any
arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]). For example −
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

Identifier
 A Python Identifier is a name used to identify a variable, function, class, module or
other object.
 An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero
or more letters, underscores and digits (0 to 9).
 Python does not allow punctuation characters such as @, $, and % within identifiers.
 Python is a case sensitive programming language. Thus, Manpower and manpower are
two different identifiers in Python.

Variables
 Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.
 Variables store a value that can be looked at or changed at a later time.
 Example:
#variables demonstrated
print ("This program is a demo of variables")
v=1
print ("The value of v is now", v)
v=v+1
print ("v now equals itself plus one, making it worth", v)
v = 51
print ("v can store any numerical value, to be used elsewhere.")
print ("for example, in a sentence. v is now worth", v)
print ("v times 5 equals", v*5)
print ("but v still only remains", v)
print ("to make v five times bigger, you would have to type v = v * 5" = v * 5)
print ("there you go, now v equals", v, "and not", v / 5)

hp 3
TALENTHOME SOLUTIONS

Operators & Operands


 Operators are special symbols that represent computations like addition and
multiplication.
 The values the operator is applied to are called Operands.

Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication etc.

Arithmetic operators in Python

Operato
Meaning Example
r

+ Add two operands or unary plus x+y

- Subtract right operand from the left or unary minus x-y

* Multiply two operands x*y

Divide left operand by the right one (always results into


/ x/y
float)

Modulus - remainder of the division of left operand by x % y (remainder


%
the right of x/y)

Floor division - division that results into whole number


// x // y
adjusted to the left in the number line

x**y (x to the
** Exponent - left operand raised to the power of right
power y)

Logical operators
Logical operators are the and, or, not operators.

Logical operators in Python

Operator Meaning Example

and True if both the operands are true x and y

or True if either of the operands is true x or y

hp 4
TALENTHOME SOLUTIONS

True if operand is false (complements the


not not x
operand)
Relational or Comparison operators

Comparison operators are used to compare values. It either returns True or False according to
the condition.

Comparision operators in Python

Operato
Meaning Example
r

> Greater that - True if left operand is greater than the right x>y

< Less that - True if left operand is less than the right x<y

== Equal to - True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

Greater than or equal to - True if left operand is greater than or


>= x >= y
equal to the right

Less than or equal to - True if left operand is less than or equal to


<= x <= y
the right

Assignment operators

Assignment operators are used in Python to assign values to variables.


a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on
the left.
There are various compound operators in Python like a += 5 that adds to the variable and
later assigns the same. It is equivalent to a = a + 5.

Assignment operators in Python

Operator Example Equivatent to

= x=5 x=5

+= x += 5 x=x+5

-= x -= 5 x=x–5

hp 5
TALENTHOME SOLUTIONS

*= x *= 5 x=x*5

/= x /= 5 x=x/5

%= x %= 5 x=x%5

//= x //= 5 x = x // 5

**= x **= 5 x = x ** 5

Special operators

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

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

Identity operators in Python

Operato
Meaning Example
r

is True if the operands are identical (refer to the same object) x is True

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

Program:
1. WAP to demonstrate all the operators.

a=10
b=3

#Arithmetic operator
print("a+b : ",a+b)
print("a-b : ",a-b)
print("a*b : ",a*b)
print("a/b : ",a/b)
print("a%b : ",a%b)
print("a power b : ",a**b)
print("a floor division b : ",a//b)

#Relational operator

hp 6
TALENTHOME SOLUTIONS

print("a == b",a == b)
print("a != b",a != b)
print("a > b",a > b)
print("a < b",a < b)
print("a >= b",a >= b)
print("a <= b",a <= b)

#Assignment Operators
c=a
print("c=a",c)
c%=a
print("c%=a",c)
c+=a
print("c+=a",c)
c-=2
print("c-=a",c)
c*=5
print("c*=a",c)

#Logical operator
i=True
j=False
print("i AND j" , i and j)
print("i OR j" , i or j)
print("NOT i" , not i)

Input and Output in Python


 The function in Python that you can use to read data from the user is:
input(): input is used to read input and by default data is of string type.

 The function to display output in python is print()

Program:
1. WAP to demonstrate input and output in python.

a=input("Enter any value")


print(a)

b=int(input("Enter any integer value"))


print(b)

2. WAP to demonstrate different type of input in python.


print ("Enter 2 nos")
x, y = input(), input()
print (x)
print (y)
print (int(x)+int(y))

hp 7
TALENTHOME SOLUTIONS

print ("Enter 2 nos")


x, y = (int(input()), int(input()))
print (x)
print (y)
print (x+y)

#space seperated input in one line


print ("Enter 2 nos(space seperated input)")
x, y = input().split()
print (int(x))
print (int(y))

#comma seperated input in one line


print ("Enter 2 nos(comma seperated input)")
x, y = (input().split(','))
print (x)
print (y)

n1=float(input("Enter float value"))


print(n1)

3. WAP for to find Area of circle.


pi=3.14
rad=int(input("Enter the radius"))
area=pi*rad*rad
print("The area is: ",area)

4. WAP for to find Area of square.


side=int(input("Enter the side"))
area=side*side
print("The area is: ",area)

5. WAP to find perimeter of rectangle.


l=int(input("Enter the length"))
b=int(input("Enter the breadth"))
peri=2*l+2*b
print("The area is: ",peri)

6. WAP for to find swap numbers.


a=int(input("Enter 1st number"))

hp 8
TALENTHOME SOLUTIONS

b=int(input("Enter 2nd number"))

print("Before swap: a=",a," and b=",b)

temp=a
a=b
b=temp
print("After swap: a=",a," and b=",b

Assignment:
1. WAP for to find Area of triangle.
2. WAP for to find Area of rectangle
3. WAP to find perimeter of square.

hp 9
TALENTHOME SOLUTIONS

Conditional Statements
 Conditionals are where a section of code is only run if certain conditions are met.
 The most common conditional in any program language, is the 'if' statement.

1. The if statement
 An if statement consists of a boolean expression followed by one or more
statements.
 Syntax:
if conditions to be met:
do this
and this
and this
 Example:
y=1
if y == 1:
print ("y still equals 1, I was just checking" )

2. The if – else statement

hp 10
TALENTHOME SOLUTIONS

 An if statement can be followed by an optional else statement, which executes when


the boolean expression is FALSE.
 Syntax:
if conditions:
run this code
else:
run this code

Here if, if condition is true then if block will be executed , if condition is false then
statement in else block will be executed.

 Example:
x = int(input("Enter a number:"))
if x%2==0:
print ("%d is even number" % x)
else:
print ("%d is odd number" % x)

3. The if – else statement (Like Ternary Operators)


 Syntax:
a if conditions else b

hp 11
TALENTHOME SOLUTIONS

First condition is evaluated, then either a or b is returned based on the Boolean value
of condition
If condition evaluates to True a is returned, else b is returned.

 Example:
>>> print('true') if True else print('false')
'true'
>>> print('true') if False else print('false')
'false'

4. The elif statement(if-else ladder)


 Syntax:
if conditions:
run this code
elif conditions:
run this code
elif conditions:
run this code
else:
run this code

 Example:
z=4
if z > 70:
print ("Something is very wrong" )

hp 12
TALENTHOME SOLUTIONS

elif z < 7:
print ("This is normal")

Programs on Conditional Statements:


1. WAP to check if the entered number is even number or odd number using Ternary
operator.
Output:
a = int(input("Enter a number"))
Enter a number 4
print("Even") if a%2 == 0 else print("Odd")
Even
OR

x=int(input("enter a number"))
Output:
enter a number7
if x%2==0:
7 is odd
print (x," is even")
else:
print (x," is odd")

2. Write a program to accept three numbers from user and display the greatest of three.
x=int(input("enter 1st number"))
y=int(input("enter 2nd number"))
z=int(input("enter 3rd number"))

if x>y and x>z:


print (x," is greatest")
elif y>x and y>z:
print(y," is greatest")
else:
print (z," is greatest")

3. WAP to find if entered year is leap year or not.


x=int(input("enter a year"))
if x%400==0:
print (x, "is a leap year")
elif x%4==0 and x%100!=0:

print (x, "is a leap year")


else:
print (x, "is not a leap year")

4. Blood donor. Take age and weight as input and find out if person is eligible for donating
blood. Valid age is >=18 and weight is >=45.
age=int(input("Enter age"))
weight=int(input("Enter weight"))
if(age>=18):
if(weight>=45):

hp 13
TALENTHOME SOLUTIONS

print("Eligible for blood donation")


else:
print("Not Eligible for blood donation as you are under weight")
else:
print("Not Eligible for blood donation as you are under age")

5. WAP to input amount from user and print minimum number of notes (Rs. 500, 100, 50,
20, 10, 5, 2, 1) required for the amount.
amount=int(input("Enter the amount"))
c2000,c500,c200,c100,c50,c20,c10,c5,c2,c1=0,0,0,0,0,0,0,0,0,0
while(amount>0):
if(amount>=2000):
amount=amount-2000
c2000=c2000+1
elif(amount>=500):
amount=amount-500
c500=c500+1
elif(amount>=200):
amount=amount-200
c200=c200+1
elif(amount>=100):
amount=amount-100
c100=c100+1
elif(amount>=50):
amount=amount-50
c50=c50+1
elif(amount>=20):
amount=amount-20
c20=c20+1
elif(amount>=10):
amount=amount-10
c10=c10+1
elif(amount>=5):
amount=amount-5
c5=c5+1
elif(amount>=2):
amount=amount-2
c2=c2+1
elif(amount>=1):
amount=amount-1
c1=c1+1

hp 14
TALENTHOME SOLUTIONS

print(c2000,"notes of 2000 rs")


print(c500,"notes of 500 rs")
print(c200,"notes of 200 rs")
print(c100,"notes of 100 rs")
print(c50,"notes of 50 rs")
print(c20,"notes of 20 rs")
print(c10,"notes of 10 rs")
print(c5,"coins of 5 rs")
print(c2,"coins of 2 rs")
print(c1,"coins of 1 rs")

6. A Calculator Program
#calculator program
#this variable tells the loop whether it should loop or not.
# 1 means loop. anything else means don't loop.
loop = 1
#this variable holds the user's choice in the menu:
choice = 0
while loop == 1:
#print what options you have
print ("Welcome to Calculator" )
num1 = int(input("Enter number 1: ") )
num2 = int(input("Enter number 2: "))
print ("your options are:")
print (" ")
print ("1) Addition")
print ("2) Subtraction")
print ("3) Multiplication")
print ("4) Division")
print ("5) Quit calculator.py")
print (" ")
choice = int(input("Choose your option: "))
if choice == 1:
print (num1, "+", num2, "=", num1 + num2)
elif choice == 2:
print (num1, "-", num2, "=", num1 – num2)
elif choice == 3:
print (num1, "*", num2, "=", num1 * num2)
elif choice == 4:
print (num1, "/", num2, "=", num1 / num2)
elif choice == 5:
loop = 0
print ("Thankyou for using calculator.py!")

Assignment:
1. WAP to print grade of student based on marks
2. BJP program.

hp 15
TALENTHOME SOLUTIONS

3. WAP to find if number is positive or negative.


4. WAP to find greater of 2 number.
5. WAP to read the value of an integer m and display 1 when m is larger than 0, 0 when m
is 0 and -1 when m is less than 0.

2. Iterative Statements
 To tell the computer to repeat a bit of code between point A and point B, until the time
comes that you need it to stop, such a thing is called a Loop.

1. The 'while' loop


 Repeats a statement or group of statements while a given condition is TRUE. It tests
the condition before executing the loop body.
 Syntax:
while condition that the loop continues:
what to do in the loop
 Example:
a=0
while a < 10:
a=a+1
print (a)
print (a)

2. The 'for' loop


 Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
 Syntax:
for var_name in range(start, end, inc/dec):
what to do in the loop
 Example:
#example 1
for i in range(1, 11, 2):

hp 16
TALENTHOME SOLUTIONS

print (i)

#example 2
for i in range(11, 1, -2):
print (i)

Programs on Iterative Statements:


1. WAP to print number from 1-10 and 10-1.(using for and while loop)
for i in range(1,11):
print(i)

#while loop,
i=1
while(i<=10):
print(i)
i+=1

2. WAP to print table of 5


n=5
for i in range(1,11):

hp 17
TALENTHOME SOLUTIONS

print(n," * ",i," = ",(n*i))

3. WAP to print summation of series (1-10)


sum=0
for i in range(1,11):
sum=sum+i
print(sum)

4. WAP to find in entered number is perfect number or not.


n = int(input("Enter any number: "))
sum1 = 0
for i in range(1, n):
if(n % i == 0):
sum1 = sum1 + i
if (sum1 == n):
print("The number is a Perfect number!")
else:
print("The number is not a Perfect number!")

5. WAP to Find GCD of two Numbers.


x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
gcd = i

print("The H.C.F. or GCD of", x,"and", y,"is", gcd)

6. WAP to print factorial of entered number


n=int(input("enter a number"))
fact = 1
for i in range(1, n+1):
fact = fact * i
print (fact, “ is factorial of ”, n)

7. WAP to print Fibonacci series


n = int(input("enter a number"))
a,b = 0,1
print (a)
print (b)
for i in range(1, n-1):

hp 18
TALENTHOME SOLUTIONS

print (a+b)
a,b = b,(a+b)

8. WAP to print
*
**
***
****
for i in range(1,5):
for j in range(1,i+1):
print("*",end="")
print()

9. WAP to print
*
**
***
****
for i in range(1,5):
for k in range(1,5-i):
print(" ",end="")
for j in range(1,i+1):
print("*",end="")
print()

10. WAP to print


****
***
**
*
for i in range(1,5):
for j in range(4,i-1,-1):
print("*",end="")
print()

11. WAP to print


1
12
123
1234
for i in range(1,5):
for j in range(1,i+1):
print(j,end="")

hp 19
TALENTHOME SOLUTIONS

print()

12. WAP to print


1
23
456
78910

k=1
for i in range(1,5):
for j in range(1,i+1):
print(k,end="")
k+=1
print()

13. WAP to print


1
22
333
4444
for i in range(1,5):
for j in range(1,i+1):
print(i,end="")
print()

14. WAP to print


1
01
101
0101
10101
k=0
l=1
for i in range(1,6):
for j in range(1,i+1):
if(i%2==0):
if(j%2==0):
print(l,end="")
else:
print(k,end="")
else:
if(j%2==0):

hp 20
TALENTHOME SOLUTIONS

print(k,end="")
else:
print(l,end="")
print()

15. WAP to print


1234
123
12
1
for i in range(1,6):
for j in range(1,6-i):
print(j,end="")
print()

16. WAP to print


54321
5432
543
54
5
for i in range(1,6):
for j in range(5,i-1,-1):
print(j,end="")
print()

17. WAP to check whether entered number is prime number or not


n=int(input("enter a number"))
i=2
while n%i!=0:
i=i+1
if n==i:
print(" it is a prime number")
else:
print("it is not a prime number")

18. WAP to Find LCM of two Numbers


x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):

hp 21
TALENTHOME SOLUTIONS

lcm = greater
break
greater += 1
print("The L.C.M. of", x,"and", y,"is", lcm)
19. WAP to find no of digits of entered number.
n=int(input("Enter number:"))
count=0
while(n>0):
count=count+1
n=n//10
print("The number of digits in the number are:",count)

20. WAP to find sum of digits of a number.


n=int(input("Enter number:"))
sum=0
while(n>0):
dig=n%10
sum=sum+dig
n=n//10
print("The sum of digits in the number are:",sum)

21. WAP to find if a number is palindrome or not


n=int(input("Enter number:"))
rev=0
temp=n
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is palindrome")
else:
print("The number is not palindrome")

22. WAP to check whether entered number is Armstrong or not


n=int(input("enter a number"))
sum=0
copy = n
while n!= 0:
rem = n % 10
sum = sum + (rem*rem*rem)
n = n / 10
if sum == copy:
print(" it is an Armstrong number")
else:
print(" it is not a Armstrong number")

hp 22
TALENTHOME SOLUTIONS

Assignment:
1. WAP to print odd no between 1-10 using for and while loop.
2. WAP to print table of n using for loop.
3. WAP to find power of a number.
4. WAP to print summation of series (20-55)
5. WAP to print summation of series of even number between 1-20
6. WAP to print summation of series of odd number between 1-20

7. WAP to print reverse of a number.


8. WAP to find prime number between 1-100.
9. WAP to find Armstrong number between 1-100.
10. WAP to find in entered number belongs to Fibonacci series or not.

Indentation
 Most of the programming languages like C, C++, Java use braces { } to define a block
of code.
 Python uses indentation.
 A code block (body of a function, loop etc.) starts with indentation and ends with the
first unindented line.
 Generally four whitespaces are used for indentation and is preferred over tabs.
 All statements with the same distance to the right belong to the same block of code, i.e.
the statements within a block line up vertically. The block ends at a line less indented
or the end of the file. If a block has to be more deeply nested, it is simply indented
further to the right.
 Eg:
from math import sqrt
n = input("Maximum Number? ")
n = int(n)+1
for a in range(1,n):
for b in range(a,n):
c_square = a**2 + b**2
c = int(sqrt(c_square)).
if ((c_square - c**2) == 0):
print(a, b, c)
 Loops and Conditional statements end with a colon ":" So, we should have said
Python is structures by colons and indentation.
 Example :
if pwd == 'apple':

hp 23
TALENTHOME SOLUTIONS

print('Logging on ...')
else:
print('Incorrect password.')

print('All done!')

 The lines print('Logging on ...') and print('Incorrect password.') are two separate code
blocks. These ones happen to be only a single line long, but Python lets you write code
blocks consisting of any number of statements.
 To indicate a block of code in Python, you must indent each line of the block by the
same amount. The two blocks of code in our example if-statement are both indented
four spaces, which is a typical amount of indentation for Python.

Structured / Sequence Data Types


5.1 Lists
 A list is a sequence of values. In a list, value can be of any type. The values in a list
are called elements or sometimes items.
 There are several ways to create a new list; the simplest is to enclose the elements in
square brackets ([ and ]):
numberList = [10, 20, 30, 40]
stringList = ['darvey', ' khaleesi', 'jon snow']
 The first example is a list of four integers. The second is a list of three strings. The
elements of a list don’t have to be the same type. The following list contains a
string, a float, an integer, and another list:
nestedList = ['spam', 2.0, 5, [10, 20]]
 A list within another list is nested.
 A list that contains no elements is called an empty list; you can create one with
empty brackets, [].
emptyList = []
>>> print (stringList, numberList, emptyList)
['darvey', ' khaleesi', 'jon snow'] [10, 20, 30, 40] []
 Python has array index and array slicing expressions on lists, denoted as a[key],
a[start : stop] or a[start : stop : step].
 Indexes are zero-based, and negative indexes are relative to the end.
 Slices take elements from the start index up to, but not including, the stop index.
 The third slice parameter, called step or stride, allows elements to be skipped and
reversed. Slice indexes may be omitted, for example a[:] returns a copy of the
entire list.

my_list = ['p','y','t','h','o','n','i','c']

print("elements 3rd to 5th")


print(my_list[2:5])

print("elements beginning to 3rd")


print(my_list[:-5])

print("elements 6th to end")


print(my_list[5:])

hp 24
TALENTHOME SOLUTIONS

print("elements beginning to end")


print(my_list[:])

Output
elements 3rd to 5th
['t', 'h', 'o']
elements beginning to 4th
['p', 'y', 't']
elements 6th to end
['n', 'i', 'c']
elements beginning to end
['p', 'y', 't', 'h', 'o', 'n', 'i', 'c']

 List are mutable, meaning, their elements can be changed unlike string or tuple.
 We can use assignment operator (=) to change an item or a range of items.

# mistake values
odd = [2, 4, 6, 8]

# change the 1st item


odd[0] = 1

# Output: [1, 4, 6, 8]
print(odd)

# change 2nd to 4th items


odd[1:4] = [3, 5, 7]

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

Output
[1, 4, 6, 8]
[1, 3, 5, 7]

Methods in List

>>> x = [1,2,3]

Method Example Output


append (item) x.append([4, 5]) [1, 2, 3, [4, 5]]
pop(indexNo) x.pop(2) [1,2,[4,5]]
count( item) x.count(2) 1
remove (item) x.remove(1) [[4,5]]
del(indexNo) – Common x=[0,1,2,3] [0,1,2]
for all del x[3]
extend (list) x.extend([4, 5]) [0, 1, 2, 4, 5]
reverse() x.reverse() [5,4,2,1,0]
index( item) x.index(4) 1

hp 25
TALENTHOME SOLUTIONS

sort() x.sort() [0,1,2,4,5]


insert (position, item) x.insert(3,3) [0,1,2,3, 4,5]
max(list) max(x) 5
min(list) min(x) 0

Python Expressions

Program :
23. WAP to print only int element in list.
list1=[1,2,3.2,5.6,10,98]

for x in list1:
if type(x) == int:
print (x)

24. WAP demonstrating use of various in-built function of list.


list1 = [1,2,5,3,4,5,5,5]
list2 = ['physics',80,'biology',75,"chemistry",90]

print (list1[0]) #first element


print (list1[0:2]) #first two elements
print (list1[0:]) #all elements from 0 onwards

print (list1.count(5)) #gives the number of occurances of the value

print (list1.index(5,3)) #value you are searching for,starting location,ending location

print (list1[0:])

list2.reverse()
print (list2[0:])

list1.sort()
print (list1[0:])
list1.sort(reverse=True)
print (list1[0:])

25. WAP Basic List Operations

hp 26
TALENTHOME SOLUTIONS

print(len([1, 2, 3]) ) #Length

print([1, 2, 3] + [4, 5, 6] ) # concatenation

print(['Hi!'] * 4 ) #Repetition

print(3 in [1, 2, 3]) # True (Membership)

for x in [1, 2, 3]:


print (x) # 1 2 3 (iteration)

26. WAP to add elements in list.


List = []
print("Intial blank List: ")
print(List)

# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)

# Adding elements to the List


# using Iterator
for i in range(1, 4):
List.append(i)
print("\nList after Addition of elements from 1-3: ")
print(List)

# Addition of List to a List


List2 = ['For', 'loop']
List.append(List2)
print("\nList after Addition of a List: ")
print(List)

# Addition of Element at specific Position (using Insert Method)


List.insert(3, 12)
List2.insert(0, 'while')
print("\nList after performing Insert Operation: ")
print(List)

# Addition of multiple elements to the List at the end (using Extend Method)
List.extend([8, 'hello', 'world'])
print("\nList after performing Extend Operation: ")
print(List)

27. Accessing elements in list.


List = ["Hello", "world", "Python"]

hp 27
TALENTHOME SOLUTIONS

# accessing a element from the list using index number


print("Accessing a element from the list")
print(List[0])
print(List[2])

# Creating a Multi-Dimensional List (By Nesting a list inside a List)


List = [['for', 'while'] , ['loops']]

# accessing a element from the Multi-Dimensional List using index number


print("Acessing a element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])

List = [1, 2, 'while', 4, 'For', 6, 'loop']

# accessing a element using negative indexing


print("Acessing element using negative indexing")
# print the last element of list
print(List[-1])
# print the third last element of list
print(List[-3])

28. WAP to demonstrate removal of elements in a List


List = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
print("Intial List: ")
print(List)

# Removing elements from List using Remove() method


List.remove(5)
List.remove(6)
print("\nList after Removal of two elements: ")
print(List)

# Removing elements from List using iterator method


for i in range(1, 5):
List.remove(i)
print("\nList after Removing a range of elements: ")
print(List)

# Removing element from the Set using the pop() method


List.pop()
print("\nList after popping an element: ")
print(List)

# Removing element at a specific location from the Set using the pop() method
List.pop(2)
print("\nList after popping a specific element: ")
print(List)

hp 28
TALENTHOME SOLUTIONS

29. WAP to find minimum and maximum element position or index in list.
def minimum(a, n):
minpos = a.index(min(a))
maxpos = a.index(max(a))

print ("The maximum is at position", maxpos + 1)


print ("The minimum is at position", minpos + 1)

a = [3, 4, 1, 3, 4, 5]
minimum(a, len(a))

30. WAP to print only unique element in list.


def unique(list1):
unique_list = []

for x in list1:
if x not in unique_list:
unique_list.append(x)

for x in unique_list:
print (x)

list1 = [10, 20, 10, 30, 40, 40]


print("the unique values from 1st list is")
unique(list1)

Assignment:
1 WAP to Check if two lists have at-least one element common. Return True or False.
2 WAP to Check if all the values in a list that are greater than a given value

5.2 Tuples
 A tuple is similar to a list.
 The difference between the two is that we cannot change the elements of a tuple
once it is assigned whereas in a list, elements can be changed.
 A tuple is created by placing all the items (elements) inside a parentheses (),
separated by comma.
 The parentheses are optional but is a good practice to write it
 A tuple can have any number of items and they may be of different types (integer,
float, list, string etc.).
 Negative Indexing: Python allows negative indexing for its sequences. The index of
-1 refers to the last item, -2 to the second last item and so on.
 Slicing: We can access a range of items in a tuple by using the slicing operator -
colon ":".
 Python Tuple Methods
Methods that add items or remove items are not available with tuple.
Only the following two methods are available.

Method Description

hp 29
TALENTHOME SOLUTIONS

count(x) Return the number of items that is equal to x


index(x) Return index of first item that is equal to x

Program:
1 Basic program on tuple
# empty tuple
my_tuple = ()
print(my_tuple)

# tuple having integers


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

# tuple with mixed datatypes


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

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

# tuple can be created without parentheses also called tuple packing


my_tuple = 3, 4.6, "dog"
print(my_tuple)

# tuple unpacking is also possible (All compulsory)


a, b, c = my_tuple
print(a)
print(b)
print(c)

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

# Output: 'p'
print(my_tuple[0])

# Output: 't'
print(my_tuple[5])

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

# nested index
print(n_tuple[0][3])
# Output: 's'

hp 30
TALENTHOME SOLUTIONS

# nested index
print(n_tuple[1][1])
# Output: 4

3 Converting list to Tuple and string to Tuple


list1 = [0, 1, 2]
print(tuple(list1))
print(tuple('python')) # string 'python' to tuple

4 Tuple repetition and concatenation


tuple3 = ('python',)*3 #repetition
print(tuple3)

print((1, 2, 3) + (4, 5, 6)) # concatenation

5 Methods of tuple
tuple2 = ('python', 2, 'a')
print(len(tuple2))

my_tuple = ('p','e','r','m','i','t')
print (my_tuple.count("p"))
print (my_tuple.index("m", 0))# give search index else will give error

5.3 Dictionaries
 Python dictionary is an unordered collection of items.
 While other compound data types have only value as an element, a dictionary has a
key: value pair.
 Dictionaries are optimized to retrieve values when the key is known.
 Creating a dictionary is as simple as placing items inside curly braces {} separated
by comma.
 An item has a key and the corresponding value expressed as a pair, key: value.
 While values can be of any data type and can repeat, keys must be of immutable
type (string, number or tuple with immutable elements) and must be unique.
 While indexing is used with other container types to access values, dictionary uses
keys. Key can be used either inside square brackets or with the get() method.
 The difference while using get() is that it returns None instead of KeyError, if the
key is not found.

Python includes the following dictionary methods −

Sr.No. Method & Description

1 dict.clear()

hp 31
TALENTHOME SOLUTIONS

Removes all elements of dictionary dict

2 dict.copy()
Returns a shallow copy of dictionary dict

3 len(dict)
Gives the total length of the dictionary. This would be equal to the number of
items in the dictionary.

4 dict.get(key, default=None)
For key key, returns value or default if key not in dictionary

6 dict.items()
Returns a list of dict's (key, value) tuple pairs

7 dict.keys()
Returns list of dictionary dict's keys

9 dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict

10 dict.values()
Returns list of dictionary dict's values

Program:
1. Creating dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary with Integer Keys


Dict = {1: 'hello', 2: 'For', 3: 'world'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)

# Creating a Dictionary with Mixed keys


Dict = {'Name': 'rohan', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

# Creating a Dictionary with dict() method

hp 32
TALENTHOME SOLUTIONS

Dict = dict({1: 'Talent', 2: 'Home', 3:'Solutions'})


print("\nDictionary with the use of dict(): ")
print(Dict)

# Creating a Dictionary with each item as a Pair


Dict = dict([(1, 'mumbai'), (2, 'city')])
print("\nDictionary with each item as a pair: ")
print(Dict)

2. Access Elements in dictionary


Dict = {1: 'Hello', 'name': 'For', 3: 'Mumbai'}

# accessing a element using key


print("Acessing a element using key:")
print(Dict['name'])

# accessing a element using key


print("Acessing a element using key:")
print(Dict[1])

# accessing a element using get() method


print("Acessing a element using get:")
print(Dict.get(3))

3. Adding Element to dictionary.


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Adding elements one at a time


Dict[0] = 'While'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Adding set of values to a single Key


Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value


Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)

# Adding Nested Key value to Dictionary


Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Good'}}
print("\nAdding a Nested Key: ")
print(Dict)

hp 33
TALENTHOME SOLUTIONS

4. Deleting elements from dictionary.


Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Python',
'A' : {1 : 'While', 2 : 'For', 3 : 'loop'},
'B' : {1 : 'Hello', 2 : 'Life'}}
print("Initial Dictionary: ")
print(Dict)

# Deleting a Key value


del Dict[6]
print("\nDeleting a specific key: ")
print(Dict)

# Deleting a Key from Nested Dictionary


del Dict['A'][2]
print("\nDeleting a key from Nested Dictionary: ")
print(Dict)

# Deleting a Key using pop()


Dict.pop(5)
print("\nPopping specific element: ")
print(Dict)

# Deleting a Key using popitem()


Dict.popitem()
print("\nPops first element: ")
print(Dict)

# Deleting entire Dictionary


Dict.clear()
print("\nDeleting Entire Dictionary: ")
print(Dict)

5. Nested Dictionary.
Dict = {1: 'India', 2: 'Country',
3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'TalentHome'}}

print(Dict)

6. Program to demonstrate various methods of Dictionary.

dict1 = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}


dict2 = dict1.copy()
print ("New Dictionary : ",dict2)

dict = {'Name': 'Zara', 'Age': 7}


print ("Value : %s" % dict.items())

hp 34
TALENTHOME SOLUTIONS

dict = {'Name': 'Zara', 'Age': 7}


print ("Value : %s" % dict.keys())

dict = {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}


print ("Values : ", list(dict.values()))

dict = {'Name': 'Zara', 'Age': 7}


print ("Start Len : %d" % len(dict))

dict.clear()
print ("End Len : %d" % len(dict))

hp 35

You might also like