Python Notes
Python Notes
print("Hello World")
Output
To Print two statements on Single Line
print("My name is Mahesh","I am in Dept AIML")
print(23)
print(12+4)
Variables
A variable is a name given to a memory location in a program.
Rules for Variable name
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
A variable name cannot be any of the Python keywords.
Example of variable : add,sub,mul,div,num1,num2….
Ex:
name = "mahesh"
age = 25
Price = 34.34
Printing Just Values
print(name)
print(age)
printing Values With Message
print("My Name is : ",name)
print("My age is : ",age)
print("Price : ",Price)
Rules for Identifiers
Printing the DATA TYPE of Variable
print(type(name))
print(type(age))
print(type(Price))
output
<class 'str'>
<class 'int'>
<class 'float'>
Data Types
Integers (+ve,-ve,Zero) (25,-25,0)
String NOTE : we can print the strings in single,double,and triple quotes
Ex :
Str1=”Hello”
Str2=’Hello’
Str3=’’’Hello’
print(str1)
print(str2)
print(str3)
Float Ex 3.4, 3.142, 0.056
Boolean Ex : True, False NOTE : T, F Should be in Capital Letters
None Ex : a = None Means no value at present
Ex :
age = 23
old = False
a = None
print(type(age))
print(type(old))
print(type(a))
Output
<class 'int'>
<class 'bool'>
<class 'NoneType'>
Keywords
Keywords are reserved words in python.
COMMENTS
Arithmetic Operators ( + , - , * , / , % , ** )
EX:
a= 2
b=4
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a%b)
print(a**b)
a +=2 #a=a+2
print(a)
a -=2 # a = a - 2
print(a)
a *=2 # a = a * 2
print(a)
a /=2 # a = a / 2
print(a)
a %=2 # a = a % 2
print(a)
Type Conversion
Ex:
a, b = 1, 2.0
sum = a + b
a, b = 1,"2"
sum = a + b #error
Input Statement
Input() Statement is used to accept values from User
Ex 1 :
#input() Statment
name = input("Enter the name : ")
age = int(input("Enter the age : "))
marks = float(input("Enter the marks : "))mahe
print("NAME : ",name)
print("AGE : ",age)
print("MARKS : ",marks)
Practice Example
Write a Program to input 2 numbers & and perform all Arithmetic operations
a = int(input("Enter the First Number : "))
b = int(input("Enter the First Number"))
add = a + b
sub = a - b
mul = a * b
div = a / b
mod = a % b
print("ADDITION : ",add)
print("SUBSTRACT : ",sub)
print("MULTIPLY : ",mul)
print("DIVISION : ",div)
print("MODULUS : ",mod)
Write a Program to input 2 floating point numbers & print their average.
a = float(input("Enter the First Floating Point Number : "))
b = float(input("Enter the Second Floating Point Number : "))
sum1 = a + b
avg = sum1/2
print("SUM : ",sum1)
print("Average : ",avg)
Write a Program to input 2 int numbers, a and b. Print True if a is greater than or equal to
b. If not print False.
a = int(input("Enter the Value of A : "))
b = int(input("Enter the Value of B : "))
if(a >= b):
print("TRUE : A is largest")
else:
print("FALSE : B is largest")
STRINGS
#STRING LENGTH
Ex :
str1 = "This is a \n Python Program"
str2 = "This is ddddddd \n a \n Python \t Program"
print(len(str1))
print(len(str2))
EX:
str1 = "COLLEGE"
print(str1[4])
print(str1[6])
Ex :
str="Apna College"
str[ 1 : 4 ] #is "pna"
str[ : 4 ] # is same as str[ 0 : 4]
str[ 1 : ] # is same as str[ 1 : len(str) ]
Output
pna
Apna
pna College
A p p l e
-5 -4 -3 -2 -1
str = “Apple”
str[ -3 : -1 ] is “pl”
A p p l e
-5 -4 -3 -2 -1
String Functions
endswith().
Ex : endswith().
str = "I am a coder."
print(str.endswith("der."))str.count(“am“) #counts the occurrence of substr in string
str.find( word )
Ex :
str = "i am a coder."
print(str.find("a coder.")) #returns 1st index of 1st occurrence
Conditional Statements
if-elif-else
SYNTAX
if(condition) : Statement1
elif(condition):
Statement2
else:
StatementN
Conditional Statements Grade students based on marks marks >= 90, grade = “A” 90 > marks >=
80, grade = “B” 80 > marks >= 70, grade = “C” 70 > m A arks p , gra n de = “D” a College
PROGRAM :
# Conditional Statements Grade students based on marks marks >= 90,
# grade = “A” 90 > marks >= 80, grade = “B” 80 > marks >= 70,
#grade = “C” 70 > m A arks p , gra n de = “D” a College
Let‘s Practice
WAP to check if a number entered by the user is odd or even.
PROGRAM
if(a % 2 == 0):
print("Given Number is EVEN NUMBER : ",a)
else:
print("Given Number is ODD NUMBER : ",a)
List Slicing
Similar to String Slicing
list_name[ starting_idx : ending_idx ] #ending idx is not included
marks = [87, 64, 33, 95, 76]
marks[ 1 : 4 ] is [64, 33, 95]
marks[ : 4 ] is same as marks[ 0 : 4] #starting index will be 0
marks[ 1 : ] is same as marks[ 1 : len(marks) ] #Ending index will be length of the string
Negative Slicing
Ex:
marks = [87, 64, 33, 95, 76]
-5 -4 -3 -2 -1
marks[ -3 : -1 ] is [33, 95]
Program :
marks = [87, 64, 33, 95, 76]
print(marks[ -3 : -1 ])
Output:
[33, 95]
List Methods
list.append(4) #adds one element at the end
EX :
list = [2,1,3]
list.append(4)
print("APPEND : ",list)
list = [2, 1, 3]
list.insert( idx, el ) #insert element at index
EX :
marks.insert(3,9)
print(marks)
list.sort( ) #sorts in ascending order
Ex:
list = [2,1,3]
list.sort() #To Print the values in Ascending Order
print("SORT : ",list)
Ex
list = [2,1,3]
list.sort(reverse=True) #To Print the values in Descending Order
print("Reverse SORT : ",list)
list.reverse( ) #reverses list
EX :
list = [87, 64, 33, 95, 76]
list.reverse()
print("Reverse List :",list)
EX
marks = [87, 64, 33, 95, 76]
marks.reverse()
print(marks)
EX :
marks.remove(4)
print(marks)
list = [2, 1, 3, 1]
list.remove(2) #removes first occurrence of element
EX :
list = [2, 1, 3, 1]
list.remove(2) #removes first occurrence of element
print(list)
list.pop( idx ) #removes element at idx [2, 3, 1]
list = [2, 1, 3, 4]
list.pop(2) #removes pop occurrence of element
print(list)
Tuples in Python
A built-in data type that lets us create immutable sequences of values. Where a List as
Mutable
tup = (87, 64, 33, 95, 76)
tup[0], tup[1]..
tup[0] = 43 #NOT allowed in python , we cannot change the value
Ex:
tup = (1,2,3,4,5)
print(tup)
print(type(tup))
tup1 = ('1.9')
print(tup1)
print(type(tup1))
# To Print individual element of Tuples
print(tup[0])
print(tup[1])
print(tup[2])
print(tup[3])
print(tup[4])
Tuple Methods
tup.index( el ) #returns index of first occurrence
tup = (2, 1, 3, 1)
tup.index(1) is 1
EX :
tup2 = (1,2,3,4,5)
print("fsdfsdf : ",tup2.index(2)) #index of 2 is 1
print("ddddd : ",tup2.index(3)) #index of 3 is 2
tup.count( el ) #counts total occurrences
up2 = (1,2,3,4,5,5,5)
tup2.count(2)
print(tup2.count(5)) #This function checks the occurrences of 5 i,e how many times 5 occurred
Let‘s Practice
WAP to ask the user to enter names of their 3 favorite movies & store them in a list.
m1 = input("Enter the first Movie Name : ")
m2 = input("Enter the Second Movie Name : ")
m3 = input("Enter the Third Movie Name : ")
l1 = [m1,m2,m3]
print("First Movie : ",l1[0])
print("Second Movie : ",l1[1])
print("Third Movie : ",l1[2])
Output:
Enter the first Movie Name : Sholay
Enter the Second Movie Name : Don
Enter the Third Movie Name : Nastik
First Movie : Sholay
Second Movie : Don
Third Movie : Nastik
WAP to check if a list contains a palindrome of elements. (Hint: use copy( ) method) [1, 2, 3, 2,
1] [1, “abc” , “abc” , 1]
Let‘s Practice WAP to count the number of students with the “A” grade in the following tuple.
Store the above values in a list & sort them from “A” to “D” . [”C” , “D” , “A” , “A” , “B” ,
“B” , “A”]
Dictionary
Dictionaries are a useful data structure for storing data in Python because they are capable of
imitating real-world data arrangements where a certain value exists for a given key.
The data is stored as key-value pairs using a Python dictionary.
o This data structure is mutable
o The components of dictionary were made using keys and values.
o Keys must only have one component.
o Values can be of any type, including integer, list, and tuple.
NOTE : As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
Example
Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
When we say that dictionaries are ordered, it means that the items have a defined order, and that
order will not change.
Unordered means that the items do not have a defined order, you cannot refer to an item by using
an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
NOTE :
1. Set items are unchangeable, but you can remove and/or add items whenever you like.
2. As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
When choosing a collection type, it is useful to understand the properties of that type. Choosing
the right type for a particular data set could mean retention of meaning, and, it could mean an
increase in efficiency or security.