0% found this document useful (0 votes)
4 views36 pages

Python?

The document provides an overview of Python data types, including integers, strings, booleans, lists, tuples, sets, and dictionaries, along with their characteristics and examples. It also covers basic operations such as floor division, string concatenation, list manipulation (like appending and removing elements), and conditional statements (if, else, and elif). Additionally, it introduces loops (for and while) and demonstrates their usage with various data structures.

Uploaded by

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

Python?

The document provides an overview of Python data types, including integers, strings, booleans, lists, tuples, sets, and dictionaries, along with their characteristics and examples. It also covers basic operations such as floor division, string concatenation, list manipulation (like appending and removing elements), and conditional statements (if, else, and elif). Additionally, it introduces loops (for and while) and demonstrates their usage with various data structures.

Uploaded by

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

python240159144141

December 11, 2023

1 Datatypes
• int
• boolean (bool)/(True/False)
• float
• string (str)
• list
• tuple
• set
• dictionary (dict)

1.1 Int
• a = 27

Floor Division (//)


• 10//3

[ ]: 10//3

[ ]: 3

[ ]:

2 String
• String are written between “…”
• String aslo written in ‘…’ (because ’ ’ can be a part of our data)

[ ]: name = "KK"
print(name)

KK

[ ]: name1 = 'kk'
print(name1)

kk

1
[ ]: print(name + name_1) # this is known as string concatenation

KKkk

[ ]: var = "kunal"
var*10

[ ]: 'kunalkunalkunalkunalkunalkunalkunalkunalkunalkunal'

[ ]: age = 21
name_2 = "kunal"
print("my name is "+name_2+ " and my age is ",age) # , is use for seprate the␣
↪data and + for String concatenation

my name is kunal and my age is 21

3 Boolean (True/False)
[ ]: print('ankur'>'arora')
# ASCII values

False

[ ]: a = 10
b = 10
a!=b # it means not equal

[ ]: False

[ ]: type(a!=b)

[ ]: bool

4 List
• List are mutable (can be edit)
• Is a datatype in which we can have multiple elements of either same or diffrent datatypes

4.0.1 if in python some words have diffrent colour (which we assign), then those words
are “keyword”

[ ]: lst = [10,20.3,"kk",True]
print(lst)

[10, 20.3, 'kk', True]

2
[ ]: type(lst)

[ ]: list

[1]: # index in python start from '0' (List/Tuples)


# list between []
lst1 = [23,45,23,12,34,2]
lst1[3]

[1]: 12

[ ]: lst1[4]=900
lst1

[ ]: [23, 45, 23, 12, 900, 2]

4.1 Slicing
• Starting index is inclusive
• ending index is exclusive (end index not display)

[ ]: # here last index is 4 but output end with 3 (Exclusive)


lst1[2:4]

[ ]: [23, 12]

[ ]: # If we dont gvive starting index then print from "0"


lst1[:4]

[ ]: [23, 45, 23, 12]

[6]: # if we not give last index then print till last element
lst1[2:]

[6]: [23, 12, 34, 2]

[ ]: lst1

[ ]: [23, 45, 23, 12, 900, 2]

[ ]: # skip elements (step size 2 then skip 1 elements) the 3rd position decide how␣
↪many step skip

lst1[0:5:2]

[ ]: [23, 23, 900]

3
[ ]: # skip elements (step size 3 then skip 2 elements)
lst1[0:5:3]

[ ]: [23, 12]

5 append() Function For adding a element &(Add one element in


end of list)
[ ]: lst1

[ ]: [23, 45, 23, 12, 900, 2]

[ ]: # add element in last


lst1.append(4)

[ ]: lst1

[ ]: [23, 45, 23, 12, 900, 2, 4, 4, 4, 4]

6 Removing elements (pop() function Remove {Default last ele-


ment in the list})
[ ]: lst1

[ ]: [23, 45, 23, 12, 900, 2, 4, 4, 4, 4, 4]

[ ]: lst1.pop()

[ ]: 4

[ ]: # Removed the 4 elements fron the list


lst1

[ ]: [23, 45, 23, 12, 900, 2]

[ ]: lst1

[ ]: [23, 45, 23, 12, 900, 2]

[ ]: # for perticular element deletion we have to give index number of that␣


↪element(which we want to delete)

lst1.pop(3)

[ ]: 12

4
[ ]: # removed 3rd index elements
lst1

[ ]: [23, 45, 23, 900, 2]

8 Tuples (All index, Slicing, stepsize same as list in tuples)


• tuple between (…)
• Tuples are immutable means it can not be Edit
[ ]: tup = (23,2.3,"kk",True)
tup[3]

[ ]: True

10 Set
10.1 In set for Adding element we use add() function instead of append()
10.2 And for deletion we use discard() function
• written between in {}
• data type can be same or diff.
• set does not allow duplicate values
• set is unorderd or unindex
• set is mutable and its elements are immutable
[ ]: s = {10,20,"kk",3.4,True,False}

[ ]: s

[ ]: {10, 20, 3.4, False, True, 'kk'}

[ ]: print("hello")

hello

[ ]: s1 = {23,23,45,23,32}
print(s1)

{32, 45, 23}

[ ]: s1.add(90) # Adding elements

5
[ ]: s1

[ ]: {23, 32, 45, 90}

[ ]: s1.discard(45) # Removing elements

[ ]: s1

[ ]: {23, 32, 90}

11

12 Dict
• it is the combination of Key and value pair (key : value)
• IS ALSO THE LIST OF TUPLES ## 3 Functions
• keys()
• values()
• items()

[ ]: d = {'name':'kk','age':21,'location':'pune'}

[ ]: type(d)

[ ]: dict

[ ]: print(d)

{'name': 'kk', 'age': 21, 'location': 'pune'}

[ ]: d['age']

[ ]: 21

[ ]: # Fuctions
d.keys()

[ ]: dict_keys(['name', 'age', 'location'])

[ ]: # Fuction
d.values()

[ ]: dict_values(['kk', 21, 'pune'])

[ ]: # Fuction
d.items()

6
[ ]: dict_items([('name', 'kk'), ('age', 21), ('location', 'pune')])

13 nested
[ ]: # nested list
lst = [1,2,3,[4,5,6,7,8,9,10]]

[ ]: lst

[ ]: [1, 2, 3, [4, 5, 6, 7, 8, 9, 10]]

[ ]: lst[3]

[ ]: [4, 5, 6, 7, 8, 9, 10]

[ ]: lst[3][6]

[ ]: 10

[ ]: # Nested list slicing


lst[3][3:6]

[ ]: [7, 8, 9]

[ ]: # nested Tuple
lst1 = [1,2,3,(4,5,6,7,8,9,10)]

[ ]: lst1[3][5]

[ ]: 9

[ ]: t = (1,2,3,(4,5,6,7,8,9,10))

[ ]: lst1 = (1,2,3,[4,5,6,7,8,9,10])

[ ]: lst1[3][5]=200

[ ]: lst1

[ ]: (1, 2, 3, [4, 5, 6, 7, 8, 200, 10])

7
14 len Fuction
14.1 calculate the length of data
[ ]: z = (1,2,3,4,5,6,78,99,0,0,67,747,2)

[ ]: len(z)

[ ]: 13

15

16

17 if & else
• these are keywords
[ ]: a = 17
if a<15:
print("a is less than 15")
else:
print("a is greater than 15")

a is greater than 15

[ ]: a = 12
if a%2==0:
print("a is an even number")
else:
print("a is an odd number")

a is an even number

18

19 elif…
[ ]: # Define one number is greater than others...
a = 10
b = 20
c = 30
if a>b and a>c:
print("a is grater number")
elif b>c and b>c:
print("b is greater number")
else:

8
print("c is greater number")

c is greater number

19.1 if contains true values and else contain false value


19.2 ‘0’ contains false value because of “Boolean”/ 0=false & 1=true (means
print else data)
[ ]: if 0:
print("KK")
else:
print("KKK")

KKK

[ ]: # because it's contain null value (false = else)


if "":
print("KK")
else:
print("KKK")

KKK

20

21 Nested if & else


[ ]: if 10<20:
if 50<30:
print("hello")
else:
print("hello kk")
else:
print("byby")

hello kk

22

23 LOOPS
• For Loop
• While Loop
• Itreable Datatypes (list,tuples,set,string,dict) in which we can use Loops

9
24

25 For Loop
[ ]: # print one by one elements
# 'x' is new assign variable
l = [1,2,3,4,5,5,6,7]
for x in l:
print(x)
print(l)

1
2
3
4
5
5
6
7
[1, 2, 3, 4, 5, 5, 6, 7]

25.1 Direct method ” for loop ” using Tuple


[ ]: for k in (12,13,1,115,16,45):
print(k)

12
13
1
115
16
45

[ ]: # sorting even or odd using for loop


k = [34,27,10,27,90,101,87]
for i in k:
if i%2==0:
print(i,"is an even number...!\n")
else:
print(i,"is an odd number\n")

34 is an even number…!

27 is an odd number

10 is an even number…!

27 is an odd number

10
90 is an even number…!

101 is an odd number

87 is an odd number

26
[ ]: # for loop in STRING
for i in 'kunal':
print(i)

k
u
n
a
l

[ ]: l1 = [34,27,10,27,90,101,45,87]
l2 = []
l3 = []

[ ]: for i in l1:
if i%2==0:
l2.append(i)
print(l2)

[34, 10, 90]

[ ]: # even number and odd seprate


for i in l1:
if i%2==0:
l2.append(i)
else:
l3.append(i)

print(l2)
print(l3)

[34, 10, 90, 34, 10, 90]


[27, 27, 101, 45, 87]

[ ]: # square of numbers
l = [1,2,3,4,5,6,7,8,9,10]

11
for i in l:
print(i*i)

1
4
9
16
25
36
49
64
81
100

[ ]: # set
s = {23,123,34,5,67,45,8}
for i in s:
print(i)

34
67
5
23
8
123
45

[ ]: # dict
# also use all function of dict...??????????????????????
d = {'name':'kunal','age':21}
for i in d:
print(i)

name
age

27

28 while loop
• always use increment in while loop
• it has three keywords :- Pass, continue, break
[ ]: x = 0
while x<10:
print("x is currently :",x)
x = x+1

12
x is currently : 0
x is currently : 1
x is currently : 2
x is currently : 3
x is currently : 4
x is currently : 5
x is currently : 6
x is currently : 7
x is currently : 8
x is currently : 9

[ ]: # also
x = 0
while x<=10:
print("x is currently :",x)
x = x+1

x is currently : 0
x is currently : 1
x is currently : 2
x is currently : 3
x is currently : 4
x is currently : 5
x is currently : 6
x is currently : 7
x is currently : 8
x is currently : 9
x is currently : 10

[ ]: # print 1-10 even or odd number using while loop


x = 1
while x<=10:
if x%2==0:
print(x,"is an even number\n")
else:
print(x,"is an odd nnumber\n")
x = x+1

1 is an odd nnumber

2 is an even number

3 is an odd nnumber

4 is an even number

5 is an odd nnumber

13
6 is an even number

7 is an odd nnumber

8 is an even number

9 is an odd nnumber

10 is an even number

[ ]:

[ ]: l = [1,2,3,4,5,5555555,6,7]
l1 = []
for i in l:
if i%2==0:
l1.append(i)
print(l1)

[2, 4, 6]

28.1 Pass
• its dose nothing at all
• USE:- to check syntax error
[ ]: x = 1
while x<10:
if x%2==0:
pass
else:
print(x)
x = x+1

1
3
5
7
9

28.2 Break
• breaks out of the current cloosest enclosing loop
[ ]: x = 0
while x<5:
print("x is :",x)
x = x+1

14
if x==3:
print("currently oon 3")
break
print("KK")

x is : 0
x is : 1
x is : 2
currently oon 3
KK

29 Input (Fuction)
• USE TYPECAST
[ ]: age = int(input("enter your age: "))

enter your age: 78

[ ]: pwd = 123
x = 0
while x<5:
otp = int(input("Enter your pwd: "))
x = x+1
if pwd==otp:
print("transaction complete")
break
else:
print("invalid retry")
if x > 4:
print("attempt exceeded")

Enter your pwd: 234


invalid retry
Enter your pwd: 123
transaction complete

29.1 continue
• goes to the top of the current clossest enclosing loop

30 operator / function
30.1 1] range()
• teh range function allows to quikly generate set (not data type set) between the specified
values
• ending point will be exclusive

15
[ ]: list(range(1,10))

[ ]: [1, 2, 3, 4, 5, 6, 7, 8, 9]

[ ]: set(range(1,11))

[ ]: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

30.2 2] step size


[ ]: list(range(1,10,3))

[ ]: [1, 4, 7]

[ ]: # Q. covert first 5 element into 100


lst = [10,20,30,40,50,60,70,80,90,100]
for i in range(0,5):
lst[i]=100

[ ]: lst

[ ]: [100, 100, 100, 100, 100, 60, 70, 80, 90, 100]

[ ]: lst = [10,20,30,40,50,60,70,80,90,100]
for i in range(0,10,3):
lst[i]=100

[ ]: lst

[ ]: [100, 20, 30, 100, 50, 60, 100, 80, 90, 100]

30.3 3] zip()
[ ]: lst1 = [1,2,3,4,5]
lst2 = ['a','b','c','d','e','f']

list(zip(lst1,lst2))

[ ]: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]

[ ]: #....
tuple(zip(lst1,lst2))

[ ]: ((1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'))

[ ]: tuple(zip(lst1,lst2,lst1))

16
[ ]: ((1, 'a', 1), (2, 'b', 2), (3, 'c', 3), (4, 'd', 4), (5, 'e', 5))

[ ]: dict(zip(lst2,lst1))

[ ]: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

[ ]: set(zip(lst1,lst2))

[ ]: {(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')}

[ ]: print(set(zip(lst1,lst2)))

{(1, 'a'), (3, 'c'), (5, 'e'), (4, 'd'), (2, 'b')}

30.4 4] max() and min()


[ ]: lst = [1,2,0,10]
max(lst)

[ ]: 10

[ ]: lst = [1,2,0,10]
min(lst)

[ ]: 0

[ ]: lst = ['kk','kkk','kkkk']
max(lst)

[ ]: 'kkkk'

31 in operator
[ ]: 'k' in ['x','y','k','z']# its just check given elements

[ ]: True

32 Library
[ ]: from random import randint
randint(0,3)

[ ]: 0

17
33

34

35 List Comprehensions
[ ]: lst = [1,2,3,4,5,6,7,8,9,10]
[x*x for x in lst] # here we written operation before the for loop
# here print operation written in start

[ ]: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

[ ]: [x%2==0 for x in lst]

[ ]: [False, True, False, True, False, True, False, True, False, True]

[ ]: [x for x in lst if x%2==0]

[ ]: [2, 4, 6, 8, 10]

[ ]: [x+2 for x in lst if x%2==0]

[ ]: [4, 6, 8, 10, 12]

[ ]: # even add 2 and odd add 3


# if & else in single line

lst = [3,5,6,8,9]
[x+2 if x%2==0 else x+3 for x in lst]

[ ]: [6, 8, 8, 10, 12]

36 split()
• output is list
[ ]: s = "hello world.. .."
s.split(" ")

[ ]: ['hello', 'world..', '..']

37
[ ]: abs(10-20)

[ ]: 10

18
38 Function & methods
• Functions are a piece of code/innstructions which we use to achieve a specific functionality.
#####
• Why do we need functions…?
• To reduce length of code and code complexity. #####
• Two types of functions:-
• 1. in-built function
• 2. user defined fucntion (UDF) #####
• There are two thing in functions:-
• 1. Function definition
• 2. Function call

39 in-bulit function
[ ]: lst = [1,1,1,2,2,2,2,2,3,3,4,5,6,7,7,7,7,7]
# lst1 = []
# for i in lst:
# if i==2:
# lst1.append(i)
# len(lst1)

k = 0
for i in lst:
if i==2:
k = k+1
print(k)

40 count() function
• Count total number of arguments in a list, tuple,…(arguments given by user)

[ ]: lst.count(2)

[ ]: 5

19
41
[ ]: lst = [1,2,3,4,5,6]
lst1= [7,8,9]
for i in lst1:
lst.append(i)
lst

[ ]: [1, 2, 3, 4, 5, 6, 7, 8, 9]

42 extend() function
• Add more than one elements in a list, tuple,…
[ ]: lst.extend([10,11,12])

[ ]: lst

[ ]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 7, 8, 9, 10, 11, 12]

43 index() function
• Give index number of specified number.
[ ]: lst = [12,243,45,4,5657,68787,989,8978978,8]
lst.index(989)

[ ]: 6

44

45 User defined functions (UDF)


• There are 4 scenarios in udf:-
• 1.Function without arguments.
• 2.Function with arguments.
• 3.Function without arguments and with return.
• 4.Function with arguments and with return. #
• there are 2 things in arguments as well:-
• 1. Accepting the arguments(While defining the functions)
• 2. Passing the arguments(While calling the functions)

20
45.1 Function without arguments.
[ ]: def addition():
a = 30
b = 20
print(a+b)

[ ]: addition()

50

[ ]: def printer():
print("hello","world")

[ ]: printer()

hello world

[ ]: # 2.....
def add(num1,num2):
print(num1+num2)

[ ]: add(2,5)

[ ]: # 3.
def add():
num1 = int(input("enter no 1: "))
num2 = int(input("enter no 2: "))
return(num1+num2)

[ ]: sum = add()

enter no 1: 23
enter no 2: 23

[ ]: print(sum)

46

[3]: lst = [1,2,3,4,5,6,7,8]


lst2 = []
def even():
for i in lst:
if i%2==0:
lst2.append(i)
# print(lst2)

21
46

47 10/10/23
[ ]: # nasted statement and scope

[ ]: def cal(num1,num2):
if num1%2==0 and num2%2==0:
return num1+num2
elif num1%2!=0 and num2%2!=0:
return abs(num1-num2)
else:
return num1*num2,num1/num2

[ ]: cal(2,2)

[ ]: 4

[ ]: cal(3,5)

[ ]: 2

[ ]: cal(2,3)

[ ]: (6, 0.6666666666666666)

[ ]: 2+2+2

[ ]: 6

[ ]:

[ ]:

lambda-map-filter
[ ]: # MAP..... its give boolean output(true and false)
def square(num1):
return num1*num1
lst = [1,2,3,4,5,6,7,8]
list(map(square,lst))

[ ]: [1, 4, 9, 16, 25, 36, 49, 64]

[37]: def even(num):


return num%2==0
lst = [1,2,3,4,5,6,7,8,9,10]

22
list(map(even,lst))

[37]: [False, True, False, True, False, True, False, True, False, True]

[ ]: # FILTER..... its filter the given data in output, acording to condition

[ ]: list(map(lambda num:num*num,[1,2,3,4,5]))

[ ]: [1, 4, 9, 16, 25]

[ ]: # *args
# we can input more than one arguments
# stores the data in tuple
def add(*args):
print(args)
return sum(args)

[ ]: add(1,2,3,4)

(1, 2, 3, 4)

[ ]: 10

[ ]: def test(*args):
for i in args:
print(i)

[ ]: test("my","kk")

my
kk

[ ]: test(("my names is kunal"))

my names is kunal

[ ]: # **kwargs
# keyword-arguments

[35]: def addition(num1,num2):


print(num1)
print(num2)
return num1+num2

[36]: addition(2,3)

2
3

23
[36]: 5

[ ]: # default arguments
def add(a=10,b=20):
return a+b

[ ]: add()

[ ]: 30

[ ]: add(2,3)

[ ]: 5

[ ]: add(2)

[ ]: 22

[ ]: add(b=2)

[ ]: 12

[ ]: def add1(a=10,b):
return a+b

File "<ipython-input-18-dd98e8304483>", line 1


def add1(a=10,b):
^
SyntaxError: non-default argument follows default argument

[ ]: def add1(a,b=10): # first non default and 2nd default


return a+b

[ ]: add1(2)

[ ]: 12

[ ]: add1(2,20) # overwite

[ ]: 22

[ ]: add1(b=10,4) #possition matter

File "<ipython-input-23-49bad0898b36>", line 1


add1(b=10,4)

24
^
SyntaxError: positional argument follows keyword argument

[2]: def acc(**kwargs):


if "debit" in kwargs:
print("debited :",kwargs["debit"])
else:
print("no debit")

[3]: acc(name='kunal',debit=2000, location = 'pune')

debited : 2000

48

49

50 object oriented programming


50.1 1.class
50.2 2.object
50.3 3.how to creaete a class and object of a class
50.4 4.creating a method function inside the class
50.5 5.inheritance
50.6 6.polymorphisum
50.7 7.special methods
[14]: # class
# 2 steps to call class 1. by class name / 2. by object of that class
# We can create multiple object's for class.

class sample:
a = 10
b = 40
print(a+b)

50

[1]: print(a)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)

25
Cell In[1], line 1
----> 1 print(a)

NameError: name 'a' is not defined

[8]: print(sample.a)

10

[9]: print(sample.b)

40

[19]: # creating object


obj_name = sample()

[12]: # call variable using object


obj_name.a

[12]: 10

[13]: # call variable using object


obj_name.b

[13]: 40

[16]: # creating new object for sample class


x = sample()
x.a

[16]: 10

[17]: x.b

[17]: 40

50.8 Overwrite a variable value of object……….


[23]: obj_name.a = 100 # here variable value not overwrite(because we overwrite␣
↪obj_name not x)

print(x.a)

10

[22]: print(x.b)

40

26
[24]: x.a = 100

[25]: print(x.a)

100

[26]: # Overwrite class value


sample.a = 200

[28]: print(sample.a)

200

[30]: sample.b = 100


print(sample.b)

100

[32]: kk = sample()
kk.a

[32]: 200

[33]: class demo:


def addition(a,b):
return a+b

[35]: d = demo()

[37]: demo.addition(10,20)

[37]: 30

[39]: d.addition(10,20) # FOR THIS WE HAVE TO USE CONSTRUCTOR OF CLASS

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[39], line 1
----> 1 d.addition(10,20)

TypeError: demo.addition() takes 2 positional arguments but 3 were given

[44]: class calculator:


def addition(a,b):
return a+b
def substraction(a,b):
return abs(a-b)

27
def multiplication(a,b):
return a*b
def division(a,b):
return a/b

[46]: calculator.substraction(2,-4) # this is the normal function call....

[46]: 6

[52]: class calculator:


def addition(self,a,b):
return a+b
def substraction(self,a,b):
return abs(a-b)
def multiplication(self,a,b):
return a*b
def division(self,a,b):
return a/b

[54]: c = calculator()
c.addition(2,3)

[54]: 5

50.9 constructor of a class:


50.10 A constructor in python is a special function, which gets automatically
called as soon as the object of the class is created.
[50]: class demo:
def __init__(self): # __init__ is a special fuction
print("my name is kunal kedari.!!!!!!!!")

[51]: k = demo() # Here we create object and that same moment called special function

my name is kunal kedari.!!!!!!!!

[1]: #18/10/23

[1]: class dog:


def __init__(self,in_breed):
self.out_breed = in_breed

[2]: sam = dog("labrador")

[3]: sam.out_breed

28
[3]: 'labrador'

[7]: # we neeed to create a object for calling variable

[10]: class dog:


species = "mammal"
def __init__(self,breed,name):
self.breed = breed
self.name = name

[11]: dog.species

[11]: 'mammal'

[12]: dog.breed

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[12], line 1
----> 1 dog.breed

AttributeError: type object 'dog' has no attribute 'breed'

[13]: sam = dog('lab','ruby')

[14]: sam.breed

[14]: 'lab'

[15]: sam.name

[15]: 'ruby'

29
50.11 1. Create a class named Circle, take the value of pi as 3.14 in a variable.
50.12 2. As soon as the object of the class is created, it should return the area
of circle with default radius as 1
50.13 3. Create a function setRadius(), which takes radius as argument and
when you call that function, it will change the original value of radius as
well and it should return the new area with new radius.
50.14 4. Create a function getCircumference()
[34]: # class circle:
# pi = 3.14
# def __init__(self,radius = 1):
# self.rad = 1
# pi = 3.14
# area = pi*(r*r)

[18]: class circle:


pi = 3.14
def __init__(self,radius=1):
self.radius = radius
self.area = radius*radius*self.pi
print(self.area)

def setRadius(self,new_radius):
self.radius = new_redius
self.area = new_radius*new_radius*self.pi
print(self.area)

def getcircumference(self):
return self.radius*self.pi*2

[19]: k = circle()

3.14

[20]: k.setRadius(2)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[20], line 1
----> 1 k.setRadius(2)

Cell In[18], line 9, in circle.setRadius(self, new_radius)


8 def setRadius(self,new_radius):
----> 9 self.radius = new_redius
10 self.area = new_radius*new_radius*self.pi
11 print(self.area)

30
NameError: name 'new_redius' is not defined

[29]: k.circumference()

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[29], line 1
----> 1 k.circumference()

AttributeError: 'circle' object has no attribute 'circumference'

51 inheritance
is a way of to access elements present in one class, using the object of another class
To create a class that inherits the functionality from another class, send the parent class as a
parameter when creating the child class:
[3]: class animal:
def __init__(self):
print("animal classs created")

def eat(self):
print('eating')

class dog(animal): # animal class is inhited in dog class


def __init__(self):
print("dog class created")

def bark(self):
print('woof')

[4]: a = animal()

animal classs created

[5]: d = dog()

dog class created

[6]: a.eat()

eating

[7]: d.bark()

31
woof

[8]: d.eat()

eating

[10]: a.bark() # because animal class is inhited in dog class

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[10], line 1
----> 1 a.bark()

AttributeError: 'animal' object has no attribute 'bark'

52 polymorphism
same object classes can share same method name (those called from same palce)…access by object
The word “polymorphism” means “many forms”, and in programming it refers to meth-
ods/functions/operators with the same name that can be executed on many objects or classes.
Polymorphism is often used in Class methods, where we can have multiple classes with the same
method name
[13]: class car:
def __init__(self,brand,model):
self.brand = brand
self.model = model

def move(self):
print("Drive !")

class ship:
def __init__(self,brand,name):
self.brand = brand
self.name = name

def move(self):
print("Sail !")

[14]: c = car('bmw','x5')

[15]: s = ship('ruby','R76')

[17]: c.move()

Drive !

32
[18]: s.move()

Sail !

53

54 format function
[2]: name = 'kunal'
age = 27
print("my name is {} and my age is {}".format(name,age))

my name is kunal and my age is 27

[3]: name = 'kunal'


age = 27
print("my name is {x} and my age is {y}".format(x=name,y=age))

my name is kunal and my age is 27

55 format function alternative


F-strings are a feature allows to embed expressions (variables or calculations) within string literals.
‘f’ can include variables or expressions inside curly braces within the string, and they will be
evaluated and replaced with their values when the string is formatted.
[1]: name = 'kunal'
age = 27
print(f"my name is {name} and my age is {age}")

my name is kunal and my age is 27

56

57 special methods
[31]: class book:
def __init__(self,name,author,pages):
print('book is created')
self.name = name
self.author = author
self.pages = pages

def __str__(self):
print("name : {}".format(self.name))
print("author : {}".format(self.author))

33
def __len__(self):
return self.pages

[32]: b = book('the nature','kk','999')

book is created

[33]: print(b)

name : the nature


author : kk

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[33], line 1
----> 1 print(b)

TypeError: __str__ returned non-string (type NoneType)

[34]: len(b)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[34], line 1
----> 1 len(b)

TypeError: 'str' object cannot be interpreted as an integer

[1]: # del b = delete the hole object

58

59 Exception Handling
try: (inside this write code)
except: (print)

59.1 it is not recommended to write logic in the except block


59.2 Use for excepted error (logiical error)
59.3 we can not handelll syntax error
in java and c (try/catch)

34
[4]: a = 10
b = '20'

print(a+b)

c = 2
d = 4
print(c+d)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[4], line 4
1 a = 10
2 b = '20'
----> 4 print(a+b)
6 c = 2
7 d = 4

TypeError: unsupported operand type(s) for +: 'int' and 'str'

[2]: try:
a = 10
b = '20'
print(a+b)
except:
print('you can not add integer with string')

you can not add integer with string

[5]: # it is not recommended to write logic in the except block

[6]: # pwd = 123


# x = 0
# while x<5:
# otp = int(input("Enter your pwd: "))
# x = x+1
# if pwd==otp:
# print("transaction complete")
# break
# else:
# print("invalid retry")
# if x > 4:
# print("attempt exceeded")

[2]: otp = 123


x = 0

35
while x<3:
try:
otp1 = int(input("enter your otp"))
if otp==otp1:
print("transaction complete")
break
else:
print("invalid retry")
x = x+1
except:
print("plese enter numeric value")
x = x+1

enter your otp567


invalid retry
enter your otp58
invalid retry
enter your otpkuyfuk
plese enter numeric value

[ ]:

36

You might also like