0% found this document useful (0 votes)
10 views21 pages

Python Basics: Variables, Data Types, and Operators

Uploaded by

mmgsg103
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)
10 views21 pages

Python Basics: Variables, Data Types, and Operators

Uploaded by

mmgsg103
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

PYTHON

It is a CASE SENSETIVE language.(uppercase like A,B,C… and lowercase like a,b,c….have


different meanings.

we can use it in gaming , data science-machine learning or ai , web-development (create


website)-use django for website formation.

LEC-1 (lecture_1.py)
print(” “) - means hum jo bhi likhenge vo as it is print hoke aa jayega.-
or usko hum output bolenge.

agar hum bich m comma (,) use krte hain to text same line m hi ayega . next
line m lane ke liye differnt print commands hi bnane padenge.

Words in double quotes “ ” , number can be written simply.

VARIABLE :-

A variable in Python is like a labeled box that stores a value, so you can use or change it
later.

**Example: name = “rakshita”**

Here, name is the variable holding the value "Rakshita".

print( ) - means variable ki value print hogi.


print(" ") - means jo likhenge vo as it is print hoga

if we use age = 25 and later on we say , age2 = age (that means age2 dene pr value 25 hi
ayegi).

RULES FOR IDENTIFIER :-

An identifier is the name you give to a variable, function, or anything you define in Python.

1. can use uppercase and lowercase letters , digits , underscore.


2. can’t use special symbols like !,#,@,$,% etc.
3. identifier can’t be start with number. name1 is valid but 1name is not valid. (keep
name simple , short and meaningful)

DATA TYPES :-
print(type(name)) - class will be str means string - (can be word ,
letter , sentence , paragraph)
print(type(age)) - class will int means integer - (can be 0,+ve,-ve)
print(type(price)) - class will be float means decimal
print(type(boolean)) - class will be bool. value will be True or False.
(with capital T & F otherwise value will be wrong.)
print(type(none)) - class will be NoneType. value will come none (means koi
value nhi di)

KEYWORDS :-

Python have its own keywords .Keywords in Python are special reserved words that have a
specific meaning to the Python interpreter — you cannot use them as variable names.

KEYWORDS LIST:-

PRINT SUM AND DIFFERENCE :-


a = 30
b = 4
sum = a+b
diff = a-b
print(sum)
print(diff)

TO COMMENT IN PYTHON FOR SINGLE LINE COMMENT :- use # , FOR MULTI


LINE COMMENT :- use “”” “””

TO COMMENT OR UN-COMMENT , SELECT THE TEXT AND CLICK ctrl + /

TYPES OF OPERATORS :-

An operator is a symbol that performs a certain operation between operands.

 Arithmetic Operators
 Relational / Comparison Operators
 Assignment Operators
 Logical Operators ( not , and , or )

**ARITHMATIC OPERATIONS**

a = 6
b = 7

print(a + b) -> addition


print(a - b) -> subtraction
print(a * b) -> multiplication
print(a / b) -> division (will always comes a floating value. e.g. 2.0)
print(a % b) -> find remainder between a & b known as MODULAR denoted by %
print(a ** b) -> find a to the power b (a^b)

LIST OF RELATIONAL/COMPARISON OPERATORS

1. == means EQUAL TO
2. != means NOT EQUAL TO
3. = means GREATER THAN EQUAL TO
4. means GREATER THAN
5. <= means LESS THAN EQUAL TO
6. < means LESS THAN

RELATIONAL/COMPARISON OPERATORS

a = 50
b = 20

print(a == b) #this expression says a=b which is FALSE so the output will
come false i.e. a boolean value.
# this means equals to == in python.
print(a != b) # this means not equal to != in python.
**ASSIGNMENT OPERATORS**

num = 10 num function ko value "10" assign ki


num = num + 10 write this in shortform as num += 10

same function can be use for -,*,/,%,**


**LOGICAL OPERATORS

NOT OPERATION**
print(not False) -> will give opp. output , means agar true likha h to
false print hoga.
print(not True)

a = 50
b = 30
print(not(a < b)) -> Will give true as print cause originally it's false.

**AND OPERATION**
val1 = True
val2 = False
print(val1 and val2) # work on two value

output TRUE tbhi hoga jb val1 and val2 dono TRUE honge. ek bhi false hua to
nhi hoga.
(can also use expression using a = 20 , b = 70)

**OR OPERATION**
print(val1 or val2) -> dono value m se agar ek bhi TRUE hua to output TRUE
aayega
(can also use expression using a = 20 , b = 70)

TYPE CONVERSION :-
**TYPE CONVERSION (AUTOMATICAALY HAPPENS)**

a = 2
b = 4.25
sum = a + b
print(sum) # 2.00 + 4.25 = 6.25

but if we put "2" then it will show error cause then it's type will be
string and python can't add things which are in different types (will only
add items if they have the same type.)

TYPE CASTING :-
**TYPE CASTING (MANUALLY HAPPENS)**

a = int("2") -> string type integer type m convert hogyi


b = 6.25
sum = a + b
print(type(a)) -> output will be int
print(sum) -> output - 8.25

INPUT IN PYTHON :-

#input se sari values STRING m convert ho jayega

1. int ( input( ) ) #output will be int.


2. input( ) # result for input( ) is always a str
3. float ( input( ) ) # output will be float

LEC-2 (lecture_2.py)
STRING :-

String is data type that stores a sequence of characters. (can be a word , sentence or
paragraph.)

str1 = "This is a string."


str2 = 'apnacollege'
str3 = """"this is a string."""

all three ways are correct but will choose DOUBLE QUOT onne.

ESCAPE SEQUENCE CHARACTER (use this cause we can’t give spacing


inside python file normally. it will show error)

1. \n means next line.

e.g. str4 = "this is a string .\\n we are creating a string in python. “

1. \t means tab space . (will provide a spacing between.)

e.g. str5 = "this is a string .\\t we are creating a string in python. "

BASIC OPERATIONS

1. concatenation (do strings ka addition) e.g. “hello” + “world” ——> “helloworld”


2. len(str) means length of str (help to calculate the length of string.)

e.g. str6 = "apna"


print(len(str6)) # output will be 4.
3. to add spacing between two strings.
str6 = "apna"
str7 = "college"
print(str6 + " " + str7) #on adding this BLANK STRING , a gap will come
between STR6 & STR7 .
print(len(str6 + " " + str7))

LENGTH CALCULATION MAI


SPACING BHI COUNT HOTI H... (imp)
INDEXING :-

on creating a STRING ,every CHARACTER got a position number(numbering will be start


from 0)

(spacing or special characters like (_) also got index i.e. number )

(index helps us to access characters.)

str = "apna college"


ch = str[0]
print(ch)

ch means CHARACTER.

SLICING :-

accessing parts of a string. (mtlb agar humne STARTING INDEX likh diya or ENDING
INDEX likh diya to uske bich ka part print hoga.)

str[ starting_idx : ending_idx ]


str = "apna college"
slice = str[0 : 4]
print(slice) -> 0 is first index and 4 is 5th index
print m ending index include nhi hoga....

IF WE WANT TO PRINT THE WHOLE COMPLETE STRING , THEN -


print(str1[0 : len(str1)])
OR
print(str1[0 :]) (ending index blank ho tb bhi end tak print hoga.)
print(str1[ : 5]) (starting index blank ho tb 0 se print hoga.)

also have index in negative…..

In POSITIVE , it goes like 0,1,2,3,4,5,…..

In NEGATIVE , it goes like ….-5,-4,-3,-2,-1 (-1 will be the ending index)

STRING FUNCTIONS:-
str = "i am studying python from apna college."
1. print([Link]("ege.")) #output will come TRUE. if not then FALSE.
2. print([Link]()) #fisrt character will be in capital alphabet.
purani str ke and koi change nhi aayega .
3. print([Link]("o" , "a")) #puri string m O ko replace krke A
aajayega.
e.g. can also replace any word like - print([Link]("python" ,
"javascript"))
4. print([Link]("o")) #pure string m O fisrt time jaahan aarha h uska
index no. print ho jayega.
aagar hum koi aisa word dalte hain jo string m h hi nhi to -1 print hoka
(which means its invalid)
5. print([Link]("a")) # yeh substring complete string m kitni baar aaya
vo number print ho jayega.

CONDITIONAL STATEMENTS :-
1. age = 16

if(age >= 18):


print("can vote & aplly for license.")
# if statement is false then kuch bhi print ni hoga.

2. light = "green"
if(light == "red"):
print("stop")
elif(light == "green"): # output will come GO , cause LIGHT =
GREEN
print("go")
elif(light == "yellow"):
print("wait")

MEANS agar LIGHT = RED hota to STOP print hota.


MEANS agar LIGHT = GREEN hota to GO print hota.
MEANS agar LIGHT = YELLOW hota to WAIT print hota.

if hamesha statement dekhega...elif tbhi dekhega jb if ne FALSE krdiya.


agar FIRST STATEMENT TRUE h to second statement ko dekhenge hi nhi chahe
vo true ho ya na ho.
e.g. num = 5
if(num > 2):
print("greater than 2")
elif(num > 3): #output is GREATER THAN 2 even though elif
statement is also true.
print("greater than 3")

IF & ILEF JITNI MRJI BAAR LIKH SKTE HAIN , BUT USE 'ELSE' ONLY ONE THAT
IN LAST
ELSE means jb upar wali sari statements FALSE dede then else apply ho
jayega.
e.g. #condition of else
num = 5
if(num > 6):
print("greater than 6")
elif(num > 8):
print("greater than 8")
else:
print("no match found")

NESTING :-

ek IF STATEMENT ke andar ek or IF STATEMENT likhna...called NESTING.


color = "blue"
if("color == blue"):
if("color == red"):
print("oops! better luck next time.")
else:
print("yah! its blue.")
else:
print("no-color is visible.")

output will be "BETTER LUCK NEXT TIME."

LEC-3 (lecture_3.py)
LISTS IN PYTHON :-

A built-in data type that stores set of values marks = [87, 64, 33, 95, 76] will write in square
brackets separated by comma. It can store elements of different types (integer, float, string,
etc.)

marks = [98, 66, 87, 64, 92, 80, 72]


print(type(marks)) # CLASS will be LIST.

HAVE SAME OPERATIONS LIKE STRING : INDEXING , LENGTH

e.g. print(marks[2]) # CONCEPT OF INDEX JUST LIKE STRING .


print(len(marks)) # string m jitne numbers honge...

in this case output will be 7 (cause there are seven marks)


# in python we can add any type of data in a single list.
e.g.
student = ["karan" ,85 , 27.3 , "delhi"]
# name - string type , 85 - int type ,27.3 -float type

STRINGS ARE IMMUTABLE (can’t be changed- like kisi bhi index ke through access krke
hum value change nhi kr skte)

LISTS ARE MUTABLE (can be changed - like kisi bhi index ke through access krke hum
value change kr skte h.)

student = ["karan" ,85 , 27.3 , "delhi"]


student[0] = "radhey" #its MUTABLE , we changed the data.
print(student) # OUTPUT - ['radhey', 85, 27.3, 'delhi']

If we give index no. which is not present in list. like if we have 4 lists but we give command
of index 5 then it will show “list index out of range”. SHOW ERROR

everything same for SLICING too. WAY OF WRITING IS DIFFERENT.

in STRING we use ,(comma) but in LIST we use :(double dots)

LIST METHODS
1. APPEND :- jo number likhenge vo list ki end m aa jayega .
e.g. list = [1, 3, 6]
[Link](8) # output will be [1, 3, 6, 8]
print(list)
2. SORT :- will arrange the list in ASCENDING ORDER.
3. [Link](reverse= True) :- will arrange the list in DECENDING ORDER.
4. [Link]() :- will reserve the list (age wale piche , piche wale
age.)
5. INSERT :- [Link](2 , 29) # this 2 is index no. (kis position pe
lana h)
# 29 is element (jo add krna chahte ho)
e.g. list = [1 , 3, 6]
then on giving command [Link](2 , 29) #OUTPUT WILL BE [1 , 3, 29 , 6]

# IF WE USE ALPHABETS RATHEN THAN NUMBER , IT WILL ARRANGE IN ALPHABATICAL


ORDER.
e.g.
list2 = ["apple" , "litchi" , "mango" , "grapes" , "pineapple"]
[Link]() # OUTPUT :- ['apple', 'grapes', 'litchi', 'mango',
'pineapple']

TUPLE :-

A built-in data type that lets us create immutable sequences of values. (data can’t be changed)

tup = (1 , 2, 3, 4) #USE SMALL BRACKET.

tup = (1, 2, 4, 6)
print(type(tup))
print(tup[2]) #INDEXING
# tup[0] = 5 NOT VALID FOR TUPLES (item assignment is not allowed - cause
TUPLES ARE IMMUTABLE

tup = (1) # when we have SINGLE ELEMENT IN TUPLE , PYTHON take it as


INTEGER.
so always write it as :- tup = (1 , )

TUPLE METHODS
1. [Link](element)
e.g. print([Link](1)) - jo element humne likha vo tuple m kis INDEX
POSITION pe aata h , it will be the output.
THAT ELEMENT SHOULD BE IN TUPLE , OTHERWISE WILL SHOW ERROR.
2. print([Link](element))
e.g. print([Link](2)) - element 2 pure tuple m kitne baar aa raha h, vo
output hoga.

LEC-4 (lecture_4.py)
DICTIONARY IN PYTHON :-

(work in pair) like key:value (normally it's word:meaning)

Dictionaries are used to store data values in key:value pairs They are unordered,
mutable(changeable) & don’t allow duplicate keys.
e.g. info = {
"name" : "Rakshita" , #string
"age" : 17 , #int
"learning" : ["coding" , "html" , "css" , "python"] , #list
"is_adult" : False , #boolean
value
"marks" : 94.3 , #float
"topics" : ("dict" , "set") , #tuple
}
#can store any kind of datatype inside our dictionary.
KEY should only be IMMUTABLE (UNCHANGED)

It doesn’t have INDEX. we can access by using the key name

e.g. dict[”key] = “value”

To change a value , we can simple say…


info["name"] = "rakshita_gupta"
print(info)
TO ADD NEW VALUE , CAN ALSO USE THE SAME PATH.
null_dict = {} #null dictionaries are written like this...

NESTED DICTIONARY

ek dictionary ke andar ek or dictionary bnana.

dict = {
"name" : "Rakshita" ,
"score" : {
"maths" : 94,
"physics" :88 ,
"chemistry" : 89
},
"grade" :"A"
}
dict is dictionary 1 and it has other score dict inside it.

DICTIONARY METHODS

1. print([Link]()) # will print all KEYS ONLY. (not include the


nested dict.)
2. print(len(dict)) # count the no. of keys present in dict. (not
include the nested dict.)
3. print([Link]()) # will print all VALUES OF KEYS. (including
nested one.)
4. print([Link]()) # all will come of pairs like [('key' ,
'value'), .....]
5. print([Link]("grade")) # willprint that value of key which we put
inside get(" ")
6. [Link]({"city" : "karnal"}) #to add a key:value pair inside
existing dictionary.

# to add mutliple new key:value pairs to existing dictionary.


[Link]({"father's name" : "mr. murli" , "mother's name" : "mrs.
sandhya"})

SET :-
Set is the collection of the unordered items. Each element in the set must be unique &
immutable.

SET will ignore the repetition and write the element only once eventhough its written
multiple times.

e.g. set = { 1, 2, 2, 2 } → repeated elements stored only once, so it resolved to {1, 2}

null_set = set( ) → empty set syntax

SET METHOD

set = {1,3,5,7,9}
1. [Link](11) # add the element(11) in existing set in the end.
2. [Link](3) # will remove this element from set.
3. [Link]() #will clear all the elements from the set.
4. [Link]() #starts to remove one element from the start.
5. UNITE :- a = {1,3,5}
b = {2,4,6}
print([Link](b)) #will unite both the set and will create a new set which
will have all elements of a & b.
# OUTPUT WILL BE {1,2,3,4,5,6}
6. INTERSECTION :- print([Link](b)) # common elements of both set
will be the output.

LEC-5 (lecture_5.py)
LOOPS :-

used to repeat instructions. (like if we have to mail 100 person then we will use loops rather
than writing the same code again and again.)

TYPES :- WHILE & FOR

WHILE:-
WHILE:-
count = 1
while count < 5 : #pehle ek condition denge
print("hello") #ek kaam [Link] tk condition TRUE hogi tb tk kaam hota
rhega.
count += 1

# PRINT NUMBERS FROM 1 TO ....(THIS i IS CALLED iterator)


i = 1
while i <= 1000 : # upto the no. u want
print(i)
i += 1
# print number is reverse order.
i = 5 # give i = last number u want.
while i >= 1:
print(i)
i -= 1
# print table or (multiplication )
i4 = 1
while i4 <= 10 :
print(3*i4)
i4 +=1
# to print to squares of continous numbers.
i6 = 1
while i6 <= 10:
print(i6 * i6)
i6 += 1

NEVER MAKE A INFINTE LOOP (LOOP SHOULD ALWAYS HAVE A STOPPING


CONDITION.)

BREAK & CONTINUE

1. Break : used to terminate the loop when encountered.

i = 1
while i<=5:
print(i)
if(i == 3):
break # 3 tk likhke stop ho jayega..
i += 1

1. Continue : terminates execution in the current iteration & continues execution of the
loop with the next iteration.

i = 1
while i<=5:
if (i == 2):
i += 1 # 2 ko chod ke sare numbers print ho jayenge.
continue
print(i)
i +=1
--> if (i == x): means agar number x ke equal h to next no. pr move kr jao
use bina print kraye.
agar x aisa no. hua jo i m exist hi nhi krta to sb kuch print ho jayega.
koi bhi no. ignore nhi hoga....

--> to print only EVEN NUMBERS


USE : if (i%2 != 0):
--> to print only ODD NUMBERS
USE : if (i%2 == 0):

FOR:-

Loops are used used for sequential traversal. For traversing list, string, tuples etc.

(num is name given by us. we can give it any name.)


list = [1,2,3]
for num in list :
print(num) # will print the number present in list.
# ek ek krke sab print ho jayenge....
nums = ["banana" , "litchi", "mango"]
for fruits in nums:
print(fruits)
else:
print("loop ended") #this else is so optional.

RANGE :-

Range functions returns a sequence of numbers, starting from 0 by default, and increments by
1 (by default), and stops before a specified number.

seq = range(5) #will print numbers upto 4 (5 not included)


for i in seq:
print(i)
CAN ALSO WRITE IT AS....
for i in range(10):
print(i)
1. for el in range(2,5):
print(el)
# range(start , stop) starting no. will be included but ending no. will NOT
.

2. for elem in range(2,10,2): # range(start , stop , step size)


print(elem) #means printed no. will be 2,4,6,8
(number will inc. with that no.) - step size
# TO PRINT ALL EVEN NUMBERS.
for even in range(2,101,2):
print(even)

# TO PRINT ALL ODD NUMBERS.


for odd in range(1,101,2):
print(odd)

# TO PRINT MULTIPLICATION ORDER. (table of 2)


for mul in range(2,21,2): # range : (table , end no. of table+1 , table)
print(mul)

# TO PRINT NUMBERS IN REVERSED ORDER.


for i2 in range(101,0,-1):
print(i2)

PASS STATEMENT :-

pass is a null statement that does nothing. It is used as a placeholder for future code.

for el in range(10): # agar khali chod denge to error aa jayega.


That’s why we need to use it.
pass

nothing will happen in code, the next command will be taken by the python.
we can add any work in this pass statement later.

LEC-6 (lecture_6.py)
FUNCTIONS :-

Block of statements that perform a specific task.

a = 5
b = 10
sum = a+b
print(sum) # later on we add more line of codes then we have to change
the no. but want the same thing i.e. SUM. That's why we use function.
#rather than writing the same thing again and again we will use FUNCTION .

def calc_sum(a , b) : # yeh input diya


sum = a+b # yeh bich m kuch work kiya
print(sum)
return sum # yeh output diya

calc_sum(2,4)
calc_sum(20,900) # yeh print bhi [Link] se print command dene ki
jrurt nhi

SOME TERMINOLOGIES:-
1. PARAMETERS :- a , b present in def calc_sum(a , b) are called
PARAMETERS.
2. FUNCTION CALL :- when we give command , calc_sum(2,4)
3. ARGUMENTS :- number present in command , 2and 4 in above .

1. def add(a,b,c,d): # for addition


sum2= a+b+c+d
print(sum2)
return sum2

add(49,2,1,0)

2. def sub(a,b): # for substraction


subtract= a-b
print(subtract)
return subtract
sub(5,2)

3. def mul(a,b): # for multiplication


multiply= a*b
print(multiply)
return multiply
mul(2,6)

4. def div(a,b): # for division


divide = a/b
print(divide)
return divide
div(4,2)

5. def avg(a,b,c): # for average


average = (a+b+c)/3
print(average)
return average
avg(2,4,6)

**# DEFAULT PARAMETER :** jb hum koi value na de , vo koi default value le.

def calc(a=1,b=1):
summation= a+b
print(summation)
return summation
calc() # a=1 and b=1 will work as the by-default values and OUTPUT= 2
RECURSION :-

When a function calls itself repeatedly. (same as LOOPS )

def show(n):
if(n == 0):
return
print(n) # pehle function ko KAAM allot krdoo.
show(n-1)

show(90) # will print counting 90,89,88,.....1

SOME TERMNOLOGIES:
1. BASE CASE : stopping condition , if(n == 0):

~ #factorial in recursion
def fact(n):
if(n == 0 or n==1):
return 1
else:
return fact(n-1)*n

print(fact(9))

LEC-7 (lecture_7.py)
Python can be used to perform operations on a file. (read & write data)

# TEXT FILE - jisme content CHARACTER FORMAT m save hota h.


e.g.- .doc , .log
# BINARY FILE - jisme kisi or type m content save hota h. e.g.
- .mov , .jpeg
**TO OPEN ANY FILE IN CODE:-**
f = open("C:/Users/DELL/Desktop/CODING/PYTHON/LECTURES/[Link]", "r")
data = [Link]()
print(data)
print(type(data))
[Link]( )

# Even though Windows shows backslashes (\\) in file paths,


Python actually supports forward slashes (/).

1. data = [Link]() # READ COMPLETE FILE.


2. data = [Link]() # CAN ALSO ENTER DATA IN ().HOW MUCH CHARCTER WE WANT
TO READ.
3. data = [Link]( ) # READ ONE LINE AT A TIME.

CHARACTERS USED FOR DIFFERENT PURPOSES :-

1. “r” - open for READING.


2. “w” - open for WRITING, truncating the file first (pehle pura data delete ho jayega fir
jo hum likhenge vo aayega. )
3. “x” - create a new file and open it for writing.
4. “a” - open a new file , appending to the end of the file if it exists. (existing data m hi
end m apna data bhi add krna is append.)
5. “b” - binary mode. (binary file ko open krne ke liye.)
6. “t” - text mode. (text file ko open krne ke liye.) - BY DEFAULT
7. “+” - open a disk file for updating (reading & writing.)

WRITING TO A FILE :-

**# WRITING TO A FILE**

f = open("C:/Users/DELL/Desktop/CODING/PYTHON/LECTURES/[Link]", "w")
[Link]("i will learn java script next.") # yeh change file m aajayega.
[Link]( )

**# APPENDING IN A FILE**

f = open("C:/Users/DELL/Desktop/CODING/PYTHON/LECTURES/[Link]", "a")
[Link]("hey its me RAKSHITA GUPTA.") # it will add in the end of
existing file.
[Link]( )

# AGAR IS NAME KI KOI FILE EXIST HI NHI KRTI TO PYTHON APNE AAP AISI FILE
CREATE KR DETA . (ONLY IN CASE OF WRITING & APPENDING.)

**# READING AND WRITING BOTH IN A FILE**


f = open("C:/Users/DELL/Desktop/CODING/PYTHON/LECTURES/[Link]", "r+")
[Link]("abc") # it will OVERWRITE . (mtlb starting m jo text tha
vo htt jayega , uski jagah yeh characters aa jayenge.)
[Link] ()

**# USE OF "w+"**


f = open("C:/Users/DELL/Desktop/CODING/PYTHON/LECTURES/[Link]", "w+")
[Link]("i am a coder.") # it will TRUNCATE (mtlb puri file clear krdega
fir likhega.)
[Link]( )

**# USE OF "a+"**


f = open("C:/Users/DELL/Desktop/CODING/PYTHON/LECTURES/[Link]", "a+")
[Link]("i am a beginner.") # it will APPEND (mtlb puri file ke end m
text likhdega.)
[Link]( )

WITH SYNTAX:-

**# FILE CLOSE KE BARE M NHI SOCHNA , WO BY DEFAULT HO JATA H (only in this
case)

# reading :-**
with open("C:/Users/DELL/Desktop/CODING/PYTHON/LECTURES/[Link]", "r") as
f:
data = [Link]( )
print(data)

**# writing :-**


with open("C:/Users/DELL/Desktop/CODING/PYTHON/LECTURES/[Link]", "w") as
f:
[Link]("new data is here.")
# output m only yeh line hi ayega baki sab earlier data delete ho
jayega...
DELETING A FILE :-

:- using the os module Module (like a code library) is a file written by another programmer
that generally has a functions we can use.

import os
[Link]("C:/Users/DELL/Desktop/CODING/PYTHON/LECTURES/[Link]")

# it will automatically delete the file.

LEC-8 (lecture_8.py)
OOPS (object oriented programming system) :-

VERY IMP FOR INTERVIEWS


To map with real world scenarios , we use OBJECT.

before making "OBJECTS" , we need to


make its blueprint called "CLASS" .
CLASS :-

→ blueprint for creating objects. (ek object ko bnane se pehle jo bhi information hame save
krni hoti h hum usko class ke andar likhte hain.)

# creating class
class Student:
name = "Rakshita"
grade = "A"

# creating objects (instances of class)


s1 = Student( )
print([Link])
print([Link])

 INIT FUNCTION :- All classes have a function called init(), which is always
executed when the object is being initiated.

class Student:
name = "Rakshita"
def __init__(self , fullname) #always add self otherwise will show
error.
[Link] = fullname
print("Adding New Student in Database.")

s1 = Student("Rakshita")
print([Link])
The self parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class.

 INSTANCE ATTRIBUTE (jo hrr object ke liye alag honge.)

like [Link] or [Link]

e.g. company (CLASS) → cars type (OBJECT) → cars ki functioning kaise stop hogi kaise
start hogi (METHODS)

 METHODS :- Methods are functions that belong to objects.

class Student:
def __init__(self , name , marks):
[Link] = name
[Link] = marks

def get_avg(self):
sum = 0
for val in [Link]:
sum += val
print("hi" , [Link] , "your avg score is : " , sum/3)

s1 = Student("tony stark" , [99,98,97])


s1.get_avg( )

[Link] = "ironman"
s1.get_avg( )

 STATIC METHODS :- Methods that don’t use the self parameter (work at class
level)

class method:
@staticmethod # decorater
def college():
print("ABC College")
# DECORATER :- Decorators allow us to wrap another function in order to
extend the behaviour of the wrapped function, without permanently modifying
it

PILLARS OF OOPS :-

 ABSTRACTION :-

→ thing which is not visible . (means)

→ Hiding the implementation details of a class and only showing the essential features to the
user.

unnecessary details ko hide krlo or user ko sirf essential part hi dikhao,


usse hi abstraction kehte hain...
class Car:
def __init__(self):
[Link] = False
[Link] = False
[Link] = False

def start(self):
[Link] = True
[Link] = True
print("car started...")

car1 = Car( )
[Link]( )

 ENCAPSULATION :-

→ Wrapping data and functions into a single unit (object).

→ putting your data and the methods that work on that data inside a "capsule" (a class).

 INHERITANCE :-

→ When one class (child / derived) derives the properties & methods of another class
(parent / base).

→ jb hume same chije hi kisi or class m bhi chiye to hum simply parent class ka name likh
denge..

e.g. class Car:


color = "black"
@staticmethod
def start( ):
print("car started...")

@staticmethod
def stop():
print("car stopped....")

class ToyotaCar(Car):
def __init__(self,name):
[Link] = name

car1 = ToyotaCar("fortuner")
car2 = ToyotaCar("prius")

print([Link])
print([Link]())
print([Link])

 TYPES OF INHERITANCE :

1. Single Inheritance (single parent class , ek hi derived child h)

📦(parent) ———> 📦(child - derived)

(above given example is of Single Inheritance.)

1. Multi-level Inheritance
📦 ——> 📦 ——> 📦 # BOX 1 is PARENT for BOX 2 .

(box 1) (box 2) (box 3) # BOX 2 is PARENT for BOX 3.

BOX 1 ki qualities BOX 2 m hongi , BOX 1 + BOX 2 ki sari qualities BOX 3 m hongi.

and so on… kitni bhi box ho skte hain….

1. Multiple Inheritance

📦+📦+📦+…… ———> 📦 (child)

PARENTS - multiple , CHILD EK HI HOGA

e.g. class A:
varA = "Welcome of class A" # A,B ARE PARENTS AND C IS A CHILD.

class B:
varB = "Welcome of class B"

class C(A , B):


varC = "welcome to class C"

c1 = C()
print([Link])
print([Link])
print([Link])

 POLYMORPHISM :-

Operator Overloading - means When the same operator is allowed to have different meaning
according to the context.

→ OPERATOR OVERLOADING :- operation to ek hi h but uske meanings vary krte hain.

(simply can say , ek hi chij ki multiple forms )

*e.g. of operator overloading*


print (1+2) #3
print( "apna" + "college") #concatenate (jod ke likh dega.)
print( [1,2,3] + [4,5,6]) # merge

OPERATORS AND DUNDER FUNCTIONS :-

class Complex:
def __init__(self , real , img):
[Link] = real
[Link] = img

def showNumber(self):
print([Link],"i +" , [Link] , "j")

def __add__(self , num2):


newReal = [Link] + [Link]
newImg = [Link] + [Link]
return Complex(newReal , newImg)

num1 = Complex(1,3) # OUTPUT : 1i + 3j


[Link]( )

num2 = Complex(4,6) # OUTPUT : 4i + 6j


[Link]( )

num3 = num1 + num2 # OUTPUT : 5i + 9j


[Link]( )

# if we use "+" it will show error (if our def add function looks like
this..def add(self , num2) we have to give command like...num3 =
[Link](num2))
#BUT IF WE USE DUNDER FUNCTION(underscore in front & end) - it will not
show error for plus sign.

SOME DUNDER FUNCTIONS ARE GIVEN BELOW…..

del KEYWORD:-

used to delete object properties or object itself. e.g. del [Link]

SUPER METHOD :-

super( ) method is used to access methods of the parent class.

e.g. class Car:


def __init__(self,type):
[Link] = type

@staticmethod
def start():
print("car started...")

@staticmethod
def stop( ):
print("car stopped...")

class ToyotaCar(Car):
def __init__(self, type , name):
super().__init__(type) # super( ) - this represents PARENT
CLASS.
[Link] = name
super().start()

car1 = ToyotaCar("electric" , "prius")


print([Link])

CLASS METHOD :-

class methods and property - notes need to be made . (PENDING WORK.)

Common questions

Powered by AI

In Python, lists are mutable, meaning their contents can change without altering their identity. This allows for items to be added, removed, or modified. For instance, changing an element by specifying its index (e.g., altering a student's name in a list) is straightforward. Conversely, strings are immutable, so any change results in a new string. For example, altering a character in a string outright isn't possible; instead, a new string must be created for a modified sequence. This impacts performance and data handling since list modifications are done in place, while operations on strings often involve additional memory allocation .

Encapsulation in Python Object-Oriented Programming is a design principle where data and the methods that operate on that data are encapsulated within a single unit or class. This structuring promotes modularity and enhances data security by restricting direct access to certain components. Encapsulation ensures only class methods can manipulate its internal state, preventing unintended interference from outside, and thus, maintaining class integrity. It's beneficial for software design as it makes code more organized, reduces complexity by hiding implementation details, and eases maintenance through well-defined interfaces .

The 'self' parameter in Python object-oriented programming is a reference to the current instance of the class. It is used within class methods to access instance attributes and methods. This parameter allows each object to keep its own data separate, ensuring that class methods can read and manipulate the instance-specific data. Without 'self', the method would not be able to understand which object it is working with .

Decorators in Python are a powerful tool that allow you to modify the behavior of functions or methods. A decorator is a function that wraps another function, augmenting its behavior without modifying its code body. Decorators are commonly used for logging, access control, and modifying input/output. For example, a @staticmethod decorator is used to declare a method as static, making it work at the class level rather than the instance level. This adds authority and functionality, extending the base function's usability in various contexts without changing its internal implementation .

Conditional statements in Python determine whether a block of code is executed based on boolean expressions. The primary structure includes 'if', 'elif', and 'else' statements. An 'if' statement checks the condition; if it evaluates to True, the subsequent block executes. If False, the program moves to 'elif' (else if) for another condition. If no 'elif' condition is true and 'else' is present, its block executes as a fallback. When nested, an 'if' can include other 'if' statements inside its block. For example, with nested conditions, an outer 'if' can evaluate one case, and if true, the inner 'if' might evaluate different criteria. This allows detailed decision trees and complex conditional logic. For example, if a variable 'color' is "blue", the outer 'if' can check this, and a nested 'if' might check if 'color' was "red". Here, the inner would be evaluated only if the outer condition was false, allowing for complex multi-criteria checks .

Static methods in Python are method functions defined within a class that do not access or modify the state of that class. Unlike instance methods, which use the 'self' parameter to operate on class instances, static methods do not require this parameter. They are marked with the @staticmethod decorator and are utilized when the method logic pertains to the class as a whole, not an instance. This makes them ideal for utility operations relevant to all instances. For example, a class that performs timing operations across different instances would implement timing algorithms as static methods, ensuring the utility remains consistent across usage cases .

Python handles operator overloading by allowing the same operator to have different meanings based on context, which is facilitated by dunder functions or "magic methods." These methods are predefined, typically surrounded by double underscores, such as __add__ for the addition operator. For instance, using '+' between integers results in arithmetic addition, while between strings, it concatenates. By implementing dunder functions like __add__ within custom classes, developers can define specific behaviors for operators when used with instances of those classes .

Polymorphism in Python allows functions or methods to operate on objects of different classes, each implementing a similar interface. Python embraces polymorphism through inheritance and duck typing rather than function overloads with multiple signatures. Unlike languages that require explicit function overloads—having multiple function definitions with different parameters—Python relies on dynamically-typed functions that apply the same operation to varied data types. For example, operator overloading uses polymorphism where operators like '+' can have different meanings depending on the operand types, such as adding numbers, concatenating strings, or merging lists, enabled by methods like __add__ .

Logical operators in Python, such as 'and', 'or', and 'not', are used to combine and modify boolean expressions, thereby dictating the outcome of decision-making. 'And' returns True if all operands are True, 'or' returns True if at least one operand is True, and 'not' inverts the truth value of the operand. These operators guide branching decisions, allowing precise control over condition evaluations. For instance, in a situation testing conditions A and B, only if both are True will an 'and' expression allow execution of subsequent code, whereas 'or' would require just one to be True. Logical constructs influence complex condition checks in control flow, impacting program logic significantly .

Inheritance in Python allows a class (the child) to incorporate properties and behaviors from another class (the parent), facilitating code reuse and the creation of hierarchical structures. In multi-level inheritance, a child class inherits from a parent class, which in turn, inherits from another parent class. This process continues, forming a chain. For example, in a structure where Box1 is a parent of Box2, and Box2 is a parent of Box3, Box3 inherits attributes and methods of both Box1 and Box2. This allows Box3 to access features from all its ancestors, demonstrating how features can be extended across multiple generations of classes in Python .

You might also like