0% found this document useful (0 votes)
13 views

Python Notes

Python is a high-level, open-source programming language developed by Guido van Rossum, known for its simplicity and ease of use. It supports various applications including data science, web development, and game development, and features a rich set of data types, operators, and control structures. The document provides an overview of Python's syntax, variable rules, data types, and examples of basic programming concepts.

Uploaded by

mahesh kanjikar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Python Notes

Python is a high-level, open-source programming language developed by Guido van Rossum, known for its simplicity and ease of use. It supports various applications including data science, web development, and game development, and features a rich set of data types, operators, and control structures. The document provides an overview of Python's syntax, variable rules, data types, and examples of basic programming concepts.

Uploaded by

mahesh kanjikar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

What is Python?

NOTE : PYTHON is a case Sensitive Language


Programming Translator Machine Code
(Compiler / Interpreter)
Python is simple & easy
 Free & Open Source
 High Level Language
 Developed by Guido van Rossum
 Portable
Uses Of Python
 In Data Science --- ML/AI
 Web Development --- Web Sites (Django)
 Games

Our First Program

print("Hello World")

Python Character Set


 Letters – A to Z, a to z
 Digits – 0 to 9
 Special Symbols - + - * / etc.
 Whitespaces – Blank Space, tab, carriage return, newline, formfeed
 Other characters – Python can process all ASCII and Unicode characters as part of data
or literals

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.

None break except in raise

False await else import pass

and continue for lambda try

True class finally is return

as def from nonlocal while

async elif if not with

assert del global or yield


Example : Addition Of Two Numbers
a= 2
b=5
sum = a + b
print(sum)

COMMENTS

# Single Line Comment Ex: # This is Single Line Comment


""" Multi Line Comment
EX :
"""Python
Is
a
High Level Language """

OPERATORS : An operator is a symbol that performs a certain operation between


operands.

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)

Relational / Comparison Operators ( == , != , > , < , >= , <= )


Ex :
a = 12
b=4
print(a>b) #True
print(a<b) #False
print(a>=b) #True
print(a<=b) #False
print(a==b) #False
print(a!=b) #True

Assignment Operators ( = , +=, -= , *= , /= , %= , **= )


EX :
a= 17

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)

Logical Operators ( not , and , or )


EX :
#Logical not Operator
a = 12
print(not a)
a=0
print(not a)
a = 12
b=4
#Logical and Operator
print(12 > 2 and 4>1)
#Logical or Operator
print(12 > 2 or 4>1)

Type Conversion
Ex:
a, b = 1, 2.0
sum = a + b
a, b = 1,"2"
sum = a + b #error

Type Casting a, b = 1, "2"


c = int(b)
sum = a + c

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 side of a square & print its area.


h = int(input("Enter the Height : "))
b = int(input("Enter the Base : "))
area = 1/2*(b*h)
print("Area of Square : ",area)

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 is data type that stores a sequence of characters.

NOTE : \n means Next Line \t means Tab Space


Ex :
str1 = "This is a \n Python Program"
print(str1)

Basic Operations on Strings


Concatenation : Joining Of Two Strings
“hello” + “world” “helloworld”

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

Indexing : Finding the Exact location of the Character

EX:
str1 = "COLLEGE"
print(str1[4])
print(str1[6])

Slicing : Accessing parts of a string


Syntax
str[ starting_idx : ending_idx ] #ending idx is not included

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

Slicing (Negative Index)

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.capitalize( ) #capitalizes 1st char


Ex :
str = "i am a coder."
print(str.capitalize()) # Captalize the First Char

str.find( word )
Ex :
str = "i am a coder."
print(str.find("a coder.")) #returns 1st index of 1st occurrence

str.replace( old, new ) #replaces all occurrences of old with new


Ex:
str = "i am a coder."
print(str.replace("am","XX"))

count() #counts the number of Occurrences


Ex:
str = "i am a coder."
print(str.count("a"))

WAP to input user’s first name & print its length.

WAP to find the occurrence of ‘$’ in a String.

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

marks=int(input("Enter the Marks : "))


if(marks >= 90):
print("Grade = A")
elif(marks >= 80):
print("Grade B")
elif(marks >= 70):
print("Grade C")
else :
print("Pass Class")

Let‘s Practice
WAP to check if a number entered by the user is odd or even.
PROGRAM

#program to check whether the given number is ODD or EVEN

a = int(input("Enter the number : "))

if(a % 2 == 0):
print("Given Number is EVEN NUMBER : ",a)
else:
print("Given Number is ODD NUMBER : ",a)

WAP to find the greatest of 3 numbers entered by the user.


PROGRAM
#Largest Of Three Numbers

a = int(input("Enter the First Number : "))


b = int(input("Enter the Second Number : "))
c = int(input("Enter the Third Number : "))

if(a > b):


if(a > c):
print("A is Largest")
else:
print("C is largest")
elif(b > c):
print("B is Largest")
else:
print("C is largest")

LISTs & TUPLES

Lists in Python (Arrays in C)


A built-in data type that stores set of values
It can store elements of different types (integer, float, string, etc.)
NOTE :
 In Python Strings are immutable , we can access the data , but we cannot change the data.
 Where as lists in python are mutable , we can assess the data and also we can change.
marks = [87, 64, 33, 95, 76] marks[0].marks[1]….
student = [”Karan” , 85, “Delhi”] #student[0], student[1].. #marks[0], marks[1]..
student[0] = “Arjun” #allowed in python , we can change the values in list.
EX:
marks=[11,22,33,44,55]
print(marks[0])
print(marks[1])
print(marks[2])
print(marks[3])
print(marks[4])
len(student) #returns length
EX:
marks = [87, 64, 33, 95, 76]
print(“Length : “,len(marks))

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

Create and print a dictionary:


thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

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.

Duplicates Not Allowed


Dictionaries cannot have two items with the same key:
Example
Duplicate values will overwrite existing values:
Thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Python Collections (Arrays)
There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate members.


 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
 Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate
members.
 Dictionary is a collection which is ordered** and changeable. No duplicate members.

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.

You might also like