Python Notes
Python Notes
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
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.
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
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
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication etc.
Operato
Meaning Example
r
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.
hp 4
TALENTHOME SOLUTIONS
Comparison operators are used to compare values. It either returns True or False according to
the condition.
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
Assignment operators
= 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.
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)
Program:
1. WAP to demonstrate input and output in python.
hp 7
TALENTHOME SOLUTIONS
hp 8
TALENTHOME SOLUTIONS
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" )
hp 10
TALENTHOME SOLUTIONS
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)
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'
Example:
z=4
if z > 70:
print ("Something is very wrong" )
hp 12
TALENTHOME SOLUTIONS
elif z < 7:
print ("This is normal")
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"))
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
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
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
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.
hp 16
TALENTHOME SOLUTIONS
print (i)
#example 2
for i in range(11, 1, -2):
print (i)
#while loop,
i=1
while(i<=10):
print(i)
i+=1
hp 17
TALENTHOME SOLUTIONS
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()
hp 19
TALENTHOME SOLUTIONS
print()
k=1
for i in range(1,5):
for j in range(1,i+1):
print(k,end="")
k+=1
print()
hp 20
TALENTHOME SOLUTIONS
print(k,end="")
else:
print(l,end="")
print()
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)
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
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.
my_list = ['p','y','t','h','o','n','i','c']
hp 24
TALENTHOME SOLUTIONS
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]
# Output: [1, 4, 6, 8]
print(odd)
# Output: [1, 3, 5, 7]
print(odd)
Output
[1, 4, 6, 8]
[1, 3, 5, 7]
Methods in List
>>> x = [1,2,3]
hp 25
TALENTHOME SOLUTIONS
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)
print (list1[0:])
list2.reverse()
print (list2[0:])
list1.sort()
print (list1[0:])
list1.sort(reverse=True)
print (list1[0:])
hp 26
TALENTHOME SOLUTIONS
print(['Hi!'] * 4 ) #Repetition
# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
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)
hp 27
TALENTHOME SOLUTIONS
# 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))
a = [3, 4, 1, 3, 4, 5]
minimum(a, len(a))
for x in list1:
if x not in unique_list:
unique_list.append(x)
for x in unique_list:
print (x)
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
Program:
1 Basic program on tuple
# empty tuple
my_tuple = ()
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
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
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.
1 dict.clear()
hp 31
TALENTHOME SOLUTIONS
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)
hp 32
TALENTHOME SOLUTIONS
hp 33
TALENTHOME SOLUTIONS
5. Nested Dictionary.
Dict = {1: 'India', 2: 'Country',
3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'TalentHome'}}
print(Dict)
hp 34
TALENTHOME SOLUTIONS
dict.clear()
print ("End Len : %d" % len(dict))
hp 35