[go: up one dir, main page]

0% found this document useful (0 votes)
5 views35 pages

pythonNotes

The document contains comprehensive notes on Python programming, covering keywords, data types, type conversion, loops, functions, and data structures such as lists, dictionaries, and sets. It includes examples of various operations, including list comprehensions, lambda functions, and dictionary comprehensions, as well as practical exercises for string manipulation and data handling. Additionally, it provides insights into commenting styles, function arguments, and the use of global and non-local variables.

Uploaded by

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

pythonNotes

The document contains comprehensive notes on Python programming, covering keywords, data types, type conversion, loops, functions, and data structures such as lists, dictionaries, and sets. It includes examples of various operations, including list comprehensions, lambda functions, and dictionary comprehensions, as well as practical exercises for string manipulation and data handling. Additionally, it provides insights into commenting styles, function arguments, and the use of global and non-local variables.

Uploaded by

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

Python notes:

#keywords and identifiers(variables)


#False,True,if,else,elif,for,while,def,try,except,finally,break
#continue,global,import,return,pass(nop)

#for x in range(5):
pass

def fun():
pass

class demo:
pass

count=8
c=5
first_name
convert to_dec

#var
Var

#single line commenting


#multiline commenting

'''
multiline commenting
multiline commenting
multiline commenting
'''

==================================

#type conversion
#implicit type conversion-perfomed by the compiler
#explicit type#may be loss of data
#implicit
a=8
b=4
c=a/b
print(c)

#explicit
num1=45
print(num1)
num1=float(num1)
print(num1)

a="456"
b=78
a=int(a)
print(a+b)

==================

#datatypes
#int,float,str,bool,list,tuple,set,dictionary,complex
#int-signed integer of unlimited length
#float-upto 15decimal places

#type()

num1=8+6j
print(type(num1))

#list(mutable)
x=[6,7,8]
print(x[2])
#tuple(immutable)
y=("hello",8,9.7)
#set(unordered collection of data,immutable)
set1={34,56,78,78}
print(set1)
#print(set1[1])

#dictionary(unordered collection of data,mutable)


student={"name":"raj","dept":"it","loc":"chn",10:"ten","marks":[56,67,78]}

print(student["dept"],student["loc"])
student["dept"]="ece"
print(student)
print(student["marks"][1])
print(student[10])

============================

#while loop
x=1

while x<=10:
print(x)
x+=1

#fibonacci series
a=0
b=1

y=1

while y<8:
print(a)
c=a+b
a=b
b=c
y+=1

#always true--unknown no of iteration

p="yes"

while p=="yes":
print("Hello developers")
p=str(input("want to print again(yes/no)"))

================================

#break and continue

for x in range(10):
if x==5:
#break
continue

print(x)

for p in range(5):
num=int(input("Enter any val:"))
if num<0:
continue
print(num)

=========================

#looping
#for loop
#while loop

#for loop

for x in range(5):
print(x)

for y in range(5,10):
print(y)

#range(startrange,endrange,stepinc/dec)
for p in range(1,8,2):
print(p)

for q in range(8,-1,-1):
print(q)

#using list
print("using list")
nums=[5,6,7,8,9]
for a in nums:
print(a)

#using indexing
names=["ram","sam","john"]

for k in range(len(names)):
print("i am",names[k])

#for loop with else

vals=[8,9,10]

for i in vals:
print(i)
else:
print("no items left in the list")

tofind="sam"
dict1={"sam":98,"john":100,"ram":67}

for st in dict1:
if st==tofind:
print(dict1[st])
break
else:
print("no entry with that name")

#while loop

==============================

#function args
#func args with default vals
def total(a=3,b=6):
print(a+b)

total(6,7)
total(5)
total()

#keyword args
def display(fname,lname):
print(fname+lname)

display(lname="Thomas",fname="Eric")

#Arbitrary args(*)

def fun(*nums):
for n in nums:
print(n)

fun(7,8,9)
fun(5,6)

===============================

x=50
def fun():
global x
x+=10
print(x,"inside func")

fun()
print(x,"outside fun")

========================

#lambda function
#nameless or anonymous function
#syntax
# lambda args:expression
from functools import reduce
d=lambda x:x*2
print(d(4))

x=lambda x,y,z:(x+y)*z
print(x(7,8,9))

#filter(),map(),reduce()
s=[1,2,3,4,5,6,7,8,9]
s1=list(filter(lambda x:(x%2==0),s))
print(s1)

s2=list(map(lambda x:x*2,s))
print(s2)

tup1=(10,20,30,40,50)
tup2=tuple(filter(lambda x:(x%3==0),tup1))
print(tup2)

tup3=tuple(map(lambda x:x+5,tup1))
print(tup3)

s=reduce(lambda a,b:a+b,[12,10,15,100])
print(s)

========================

'''def fun():

fun()

fun()'''

def fact(x):
if x==1:
return 1
else:
return(x+fact(x-1))

print(fact(5))

===================

#list function
#ordered collection,mutable
x=[] #empty list
x=[1,2,3,67,89,"python"]

#indexing/positioning
print(x[3])

#negative indexing
print(x[-2])

#slicing
print(x[1:4])
print(x[1:])
print(x[:5])
print(x[:])
print(x[::-1])

#append(),extend()--adding elements in the list


x.append(100)
print(x)
x.extend([25,50,60])
print(x)
#concatenation(+) and repetition(*)
lista=[10,20,30]
listb=[40,50,60]
print(lista+listb)

print(lista*3)

#removing the list elements


#remove(val),pop(pos),clear(),del

lista.remove(30)
print(lista)

print(listb.pop(2))
print(listb)

listb.clear()
print(listb)

del lista
#print(lista)

#other functions
#index(),insert(pos,val),sort(),reverse(),copy(),count()

x.insert(4,99)
print(x)

print(x.index('python'))
d=[11,8,7,34,5,10]
d.reverse()
print(d)
d.sort()
print(d)
d.sort(reverse=True)
#d.reverse()
print(d)
e=d.copy()
print(e)
print(x.count(50))
x.append(50)
print(x.count(50))

#list comprehension
a=[x*3 for x in range(5)]
print(a)
even=[x if x%2==0 else "odd" for x in range(10)]
print(even)

#list comprehension with lambda case

p=[(lambda x:x+1)(x) for x in range(10)]


print(p)

=================================

#non local variables

def outside():
x=45
def inside():
nonlocal x
x=90
print(x,"inner function")
inside()
print(x,"outside function")

outside()

========================

a=lambda x: True if(x>10 and x<20) else False

print(a(5))

b=lambda x:x>10 and x<20


print(b(12))

var=[5,5,12,15,20]
c=list(filter(lambda x:x>10 and x<20,var))
print(c)

p=lambda x:x*2 if x<10 else (x*3 if x<20 else x)

print(p(25))

==============================

#list comprehension
a=[x*3 for x in range(5)]
print(a)

even=[x if x%2==0 else "odd" for x in range(10)]


print(even)

#list comprehension with lambda case

p=[(lambda x:x+1)(x) for x in range(10)]


print(p)

p=[(lambda x:x)(x)for x in range(10) if x%2==0]


print(p)
p=[(lambda x:x)(x) if x%2==0 else "odd" for x in range(10)]
print(p)

=====================================

1.Given 2 strings, s1 and s2, create a new string


by appending s2 in the middle of s1
Given:

s1 = "java"
s2 = "program"
o/p:
japrogramva

2. Find all occurrences of “USA” in given string ignoring the case


Given:

str1 = "Welcome to USA. usa awesome, isn't it?"

Expected Outcome:

The USA count is: 2


3. Given an input string, count occurrences of all characters within a string
Given:

str1 = "Apple"

Expected Outcome:

{'A': 1, 'p': 2, 'l': 1, 'e': 1}

4. Given a Python list. Turn every item of a list


into its square (using list comprehension)
aList = [1, 2, 3, 4, 5, 6, 7]
Expected output:

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

5. Add item 7000 after 6000 in the following Python List


list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
Expected output:

[10, 20, [300, 400, [5000, 6000, 7000], 500], 30, 40]

6. Check if a value 200 exists in a dictionary


sampleDict = {'a': 100, 'b': 200, 'c': 300}
Expected output:

True

7. Iteration using dictionary


sampleDict = {
'Physics': 82,
'Math': 65,
'history': 75
}
if value is between 62 and 67, then add 10 with the value

8. Return a set of all elements in either A or B, but not both


set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}

Expected output:

{20, 70, 10, 60}

9.Update set1 by adding items from set2, except common items


set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}

Expected output:

{70, 10, 20, 60}

10. Swap the following two tuples


tuple1 = (11, 22)
tuple2 = (99, 88)

Expected output:

tuple1 = (99, 88)


tuple2 = (11, 22)

11. Counts the number of occurrences of item 50 from a tuple


tuple1 = (50, 10, 60, 70, 50)

Expected output:

===========================================

#string functions
#ordered sequence of characters
#immutable

str1="hello"
str2='python'
str3='''welcome to our
website'''
print(str3)

#indexing
print(str1[2])

#negative indexing
print(str1[-2])

#slicing
print(str1[1:3])

#str2[1]="i"#type error
str2="developers"
print(str2)

#del -to delete the string var

#concatenation(+),repetition("*")
print(str1+str2)
print(str1*2)

#len(),enumerate()
print(len(str1))
print(list(enumerate(str1)))
#upper(),lower(),join(),split(),find(),replace()
print(str1.upper())
print("ManaGer".lower())
print(" ".join(str1))
print(str3.split())
print(str1.find('i'))
print("good morning".replace("good","happy"))

for p in str1:
print(p)

========================================================

#set functions
#unordered collection,immutable
#empty set
set1=set()
print(type(set1))
set1={10,20,30,"hello",79.8}
print(set1)

#set membership test(in,not in)


print(30 in set1)

#updating the set


#add(),update()

set1.add(56)
print(set1)

set1.update([25,55,65])

print(set1)

set1.add(56)
print(set1)

#deleting the set elements


#discard(val),remove(val),pop(),clear(),del

set1.discard(156)
print(set1)
#set1.remove(155)
print(set1)

print(set1.pop(),"is deleted")
print(set1)
set1.clear()
print(set1)
#set operation
#union(|),intersection(&),difference(-),symmetric difference(^)

a={10,20,30,40,50}
b={30,40,60,70,80}

print(a|b)

print(a&b)

print(a-b)
print(b-a)

print(a^b)

#iteration
for p in a:
print(p)

==========================================

#dictionary function

dict1={"name":"Raj","level":"seniorsoftware engineer","empid":7890}
print(dict1["empid"])

#get()
print(dict1.get("name"))
print(dict1.get("city"))
#print(dict1["city"])#key error
#adding/updating the dict elements

dict1["name"]="priya"
print(dict1)

dict1["city"]="chennai"

print(dict1)

#removing the elements from dict


#pop(),clear(),del

print(dict1.pop("empid"))
print(dict1)

#other functions
#keys(),values(),items()
print(dict1.keys())
print(dict1.values())
print(dict1.items())

#iteration
for k,v in dict1.items():
print(k,v)
#dictionary comprehension

a={x:x*x for x in range(5)}


print(a)

p={"pdt1":25,"pdt2":50,"pdt3":60}

newdict={key:val*2 for key,val in p.items()}


print(newdict)

newdict1={key:val for key,val in p.items() if val%2==0}


print(newdict1)

#dictionary membership test(applicable for keynames--(in,not in))


print("pdt2" not in p)

================================================

'''
1.Given 2 strings, s1 and s2, create a new string
by appending s2 in the middle of s1
Given:
s1 = "java"
s2 = "program"
'''
s1="java"
s2="program"
print(s1[0:2]+(s2)+(s1[2:]))
'''
2. Find all occurrences of “USA” in given string ignoring the case
Given:"Welcome to USA. usa awesome, isn't it?"
'''
str1="Welcome to USA. usa awesome, isn't it?"
str1=str1.lower()
print(str1.count("usa"))
'''
3. Given an input string, count occurrences of all characters
within a string
Given:
str1 = "Apple"
'''
q3="Apple"
values={letter:q3.count(letter) for letter in q3}
print(values)
'''
4. Given a Python list. Turn every item of a list
into its square (using list comprehension)
aList = [1, 2, 3, 4, 5, 6, 7]
'''
aList = [1, 2, 3, 4, 5, 6, 7]
new_list=[x**2 for x in aList]
print(new_list)
'''
5. Add item 7000 after 6000 in the following Python List
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
Expected output:
'''
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
list1[2][2].insert(2,700)
print(list1)
'''
6.Check if a value 200 exists in a dictionary
sampleDict = {'a': 100, 'b': 200, 'c': 300}
Expected output:

'''
sampleDict = {'a': 100, 'b': 200, 'c': 300}
if 200 in sampleDict.values():
print("True")
else:
print("False")
'''
7. Iteration using dictionary
sampleDict = {
'Physics': 82,
'Math': 65,
'history': 75
}
if value is between 62 and 67, then add 10 with the value
'''
sampleDict = {'Physics': 82,'Math': 65,'history': 75}
newdict={key:val+10 if 62<val<67 else val for key,val in
sampleDict.items() }
print(newdict)
'''
8. Return a set of all elements in either A or B, but not both
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}
Expected output:
{20, 70, 10, 60}
'''
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}
print(set1^set2)
'''
9.Update set1 by adding items from set2, except common items
set11 = {10, 20, 30, 40, 50}
set22 = {30, 40, 50, 60, 70}
Expected output:
{70, 10, 20, 60}
'''
set11 = {10, 20, 30, 40, 50}
set22 = {30, 40, 50, 60, 70}
print(set11^set22)
'''
10. Swap the following two tuples
tuple1 = (11, 22)
tuple2 = (99, 88)

Expected output:
tuple1 = (99, 88)
tuple2 = (11, 22)
'''
tuple1 = (11, 22)
tuple2 = (99, 88)
tuple3=tuple1
tuple4=tuple2
tuple1=tuple4
tuple2=tuple3
print("tuple1:",tuple1)
print("tuple2:",tuple2)
'''
11. Counts the number of occurrences of item 50 from a tuple
tuple1 = (50, 10, 60, 70, 50)
Expected output:
2
'''
tuple1 = (50, 10, 60, 70, 50)
print(tuple1.count(50))

========================================================

'''
1.Given 2 strings, s1 and s2, create a new string
by appending s2 in the middle of s1
Given:
s1 = "java"
s2 = "program"
'''
s1="java"
s2="program"
print(s1[0:2]+(s2)+(s1[2:]))
'''
2. Find all occurrences of “USA” in given string ignoring the case
Given:"Welcome to USA. usa awesome, isn't it?"
'''
str1="Welcome to USA. usa awesome, isn't it?"
str1=str1.lower()
print(str1.count("usa"))
'''
3. Given an input string, count occurrences of all characters
within a string
Given:
str1 = "Apple"
'''
q3="Apple"
values={letter:q3.count(letter) for letter in q3}
print(values)
'''
4. Given a Python list. Turn every item of a list
into its square (using list comprehension)
aList = [1, 2, 3, 4, 5, 6, 7]
'''
aList = [1, 2, 3, 4, 5, 6, 7]
new_list=[x**2 for x in aList]
print(new_list)
'''
5. Add item 7000 after 6000 in the following Python List
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
Expected output:
'''
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
list1[2][2].insert(2,700)
print(list1)
'''
6.Check if a value 200 exists in a dictionary
sampleDict = {'a': 100, 'b': 200, 'c': 300}
Expected output:

'''
sampleDict = {'a': 100, 'b': 200, 'c': 300}
if 200 in sampleDict.values():
print("True")
else:
print("False")
'''
7. Iteration using dictionary
sampleDict = {
'Physics': 82,
'Math': 65,
'history': 75
}
if value is between 62 and 67, then add 10 with the value
'''
sampleDict = {'Physics': 82,'Math': 65,'history': 75}
newdict={key:val+10 if 62<val<67 else val for key,val in
sampleDict.items() }
print(newdict)
'''
8. Return a set of all elements in either A or B, but not both
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}
Expected output:
{20, 70, 10, 60}
'''
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 50, 60, 70}
print(set1^set2)
'''
9.Update set1 by adding items from set2, except common items
set11 = {10, 20, 30, 40, 50}
set22 = {30, 40, 50, 60, 70}
Expected output:
{70, 10, 20, 60}
'''
set11 = {10, 20, 30, 40, 50}
set22 = {30, 40, 50, 60, 70}
print(set11^set22)
'''
10. Swap the following two tuples
tuple1 = (11, 22)
tuple2 = (99, 88)

Expected output:
tuple1 = (99, 88)
tuple2 = (11, 22)
'''
tuple1 = (11, 22)
tuple2 = (99, 88)
tuple3=tuple1
tuple4=tuple2
tuple1=tuple4
tuple2=tuple3
print("tuple1:",tuple1)
print("tuple2:",tuple2)
'''
11. Counts the number of occurrences of item 50 from a tuple
tuple1 = (50, 10, 60, 70, 50)
Expected output:
2
'''
tuple1 = (50, 10, 60, 70, 50)
print(tuple1.count(50))

=========================================================

#inheritance
#single level inheritance
# multiple inheritance
# multilevel inheritance
#hierarchial inheritance

#multiple inheritance
#two or more base class, combines to form a child class
class A:

def getval1(self):
self.val1=int(input("Enter the val1:"))

class B:
def getval2(self):
self.val2=int(input("Enter the val2:"))

class C:
def getval3(self):
self.val3=int(input("Enter the val3:"))

class demo(A,B,C):
val4=60

def calculate(self):
res=(self.val1*self.val2*self.val3)/self.val4
print("Final Result:",res)

obj=demo()
obj.getval1()
obj.getval2()
obj.getval3()
obj.calculate()

==================================================

#hierarchial inheritance
class student:

def getdata(self):
self.name=str(input("Enter the name:"))
self.rno=int(input("Enter the rno:"))

class civil(student):
def getfee(self):
#self.getdata()
print("depatment:civil")
self.fee=45000
print("Name:",self.name)
print("Rno:",self.rno)
print("Fee:Rs.",self.fee)

class it(student):

def getfee1(self):
self.getdata()
print("depatment:it")
self.fee=55000
print("Name:",self.name)
print("Rno:",self.rno)
print("Fee:Rs.",self.fee)

class ece(student):
def getfee2(self):
self.getdata()
print("depatment:ece")
self.fee=65000
print("Name:",self.name)
print("Rno:",self.rno)
print("Fee:Rs.",self.fee)

obj1=civil()
obj2=it()
obj3=ece()
print("civil dept")
obj1.getdata()
obj1.getfee()
print("it dept")
obj2.getfee1()
print("ece dept")
obj3.getfee2()

=============================

#inheritance
#single level inheritance
# multiple inheritance
# multilevel inheritance
#hierarchial inheritance

#single level-
#one parent and one child class

class book:
def getinfo(self):
self.bname=str(input("Enter the bookname:"))
self.author=str(input("Enter the author:"))
self.price=int(input("Enter the price:"))

class customer(book):

def custinfo(self):
print("Book Name:",self.bname)
print("Price:",self.price)
self.name=str(input("Enter ur name:"))
self.qty=int(input("Enter the quantity:"))
print("Amount to be paid",self.price*self.qty)

obj=customer()
obj.getinfo()
obj.custinfo()

=============

#encapsulation
class laptop:
def __init__(self):
self.a=67
self.__price=70000

def sell(self):
print(self.__price,"private variable")
print(self.a,"public variable")

def update_values(self,x):
self.__price=x

obj=laptop()
obj.sell()
obj.__price=75000
obj.a=89
obj.sell()
obj.update_values(75000)
obj.sell()

=======================

'''
1.Return the Next Number from the Integer Passed
Create a function that takes a number as an argument, increments the number by +1
and returns the result.
'''
def increment(x):
x+=1
return x
m=int(input("enter a number"))
func=increment(m)
print(func)

'''
2.a.Given a string of even length, return the first half. So the
string "WooHoo" yields "Woo".
first_half('WooHoo') → 'Woo'
first_half('HelloThere') → 'Hello'
first_half('abcdef') → 'abc'
'''
def half_string(x):
y=int(len(x)/2)
return x[:y]
print(half_string('WooHoo'))
print(half_string('HelloThere'))
print(half_string('abcdef'))

'''
b.Given a string, return a version without the first and last
char, so "Hello" yields "ell". The string length will be at least
2.
without_end('Hello') → 'ell'
without_end('java') → 'av'
without_end('coding') → 'odin'
'''
def without_end(x):
y=int(len(x))
return x[1:y-1]
print(without_end('Hello'))
print(without_end('java'))
print(without_end('coding'))
'''
3.Given 2 int arrays, a and b, each length 3, return a new array
length 2 containing their middle elements.

middle_way([1, 2, 3], [4, 5, 6]) → [2, 5]

middle_way([7, 7, 7], [3, 8, 0]) → [7, 8]


middle_way([5, 2, 9], [1, 4, 5]) → [2, 4]
'''

def middle_way(x, y):


if len(x) % 2 != 0:
middle_x = int((len(x) + 1) / 2) - 1
else:
middle_x = int(len(x) / 2) - 1
if len(y) % 2 != 0:
middle_y = int((len(x) + 1) / 2) - 1
else:
middle_y = int(len(x) / 2) - 1
new_list = []
new_list.append(x[middle_x])
new_list.append(y[middle_y])
return new_list

print(middle_way([1, 2, 3], [4, 5, 6]))


print(middle_way([7, 7, 7], [3, 8, 0]))
print(middle_way([5, 2, 9], [1, 4, 5]))
'''
4.Python Program to Print Largest Even and Largest Odd Number in a
List
'''
def even_odd(lista):
odd_list=list(filter(lambda x:x%2!=0,lista))
even_list=list(filter(lambda x:x%2==0,lista))
odd_list.sort()
even_list.sort()
even=even_list[len(even_list)-1]
odd=odd_list[len(odd_list)-1]
return (even,odd)
print(even_odd([7,8,1,3,5,6,2,9,10,4]))
'''
5.The program takes a list and swaps the first and last value of
the list using for loop
'''

def reverse_element(lista):
new_list = [x for x in lista[1:len(lista) - 1]]
new_list.insert(0, lista[len(lista) - 1])
new_list.append(lista[0])
print(new_list)

reverse_element([1, 2, 3, 4])

'''
6.The program takes a string and checks if a substring is present
in the given string using find() DOUBT
'''
def substring_check(string1):
string1=string1.lower()
lista=string1.split()
x=len(lista)
seta=set(lista)
y=len(seta)
if x!=y:
return "Words are repeated"
else:
return "no repetition"

print(substring_check("Hi,hi my name is is Sam"))


'''
7.The program takes a number from the user and generates a
dictionary that contains numbers (between 1 and n) in the form
(x,x*x).
'''
num1=int(input("Enter a number"))
dict1={x:x*x for x in range(num1+1)}
print(dict1)
'''
8.Using set, do the following operations:
union,intersection,difference
'''
def set_functions(a,b):
set_a=set(a)
set_b=set(b)
print("The union is:",set_a|set_b)
print("The intersection is:",set_a&set_b)
print("The difference is:",set_a-set_b)
set_functions((3,4,5,6),(3,6,7,9))
'''
9.Write a function to calculate area and perimeter of a rectangle.
Return area and perimeter output. Send these outputs to the
division function
'''
def perimeter_rectangle(l,b):
return 2*(l+b)
def area_rectangle(l,b):
return l*b
a=int(input("Enter a number"))
c=int(input("Enter another number"))
x=perimeter_rectangle(a,c)
y=area_rectangle(a,c)

def division(num1,num2):
print(num1/num2)
division(x,y)
'''
10.Demonstrate an example program for Recursive Function.
'''
def factorial(x):
if x==1:
return 1
else:
return x*factorial(x-1)

print(factorial(5))

=============================

class sample:
a=9

try:
obj=sample()
print(obj.a)
print(obj.b)

except AttributeError:
print("attribute is not defined in the class")

#name error

print(a)

#module not found error


import xyz

#lookup errors
#keyerror,index error
a=[8,9,10]
print(a[5])

#raising the error


try:
x=int(input("Enter a number:"))
if x<0:
raise ValueError("negative vals are not allowed")

except ValueError as msg:


print(msg)
==========================================

#exception handling
#try,except,else,finally
try:
a=int(input("Enter any no:"))
b=int(input("Enter any no:"))

except ValueError:
print("enter only integers")

except ZeroDivisionError:
print("denominator should not be 0")
else:
print(a/b)
finally:
print("end")

===========================

#raise keyword
try:
x=int(input("Enter any value:"))
if x<0:
raise ValueError("negative values are not accepted")
except ValueError:
print("negative values are not accepted")

===============================

#assert stmt
#AssertionError

try:
x=int(input("Enter any val:"))
assert x!=0,"invalid"
except AssertionError as msg:
print(msg)

==================================

#exception handling
#try,except,else,finally
try:
a=int(input("Enter any no:"))
b=int(input("Enter any no:"))
print(a/b)

except ValueError:
print("enter only integers")

except ZeroDivisionError:
print("denominator should not be 0")
========================

try:
print(a)

except NameError:
print("error")

=====================

#polymorphism
#same function names with different work

class sample:

def calculate(self):
self.x=int(input("Enter xval:"))
self.y=int(input("Enter y val:"))
print(self.x+self.y)

def combine(self):#string concatenation


self.a=str(input("Enter fname:"))
self.b=str(input("Enter lname:"))
print(self.a+self.b)

class sample1:

def calculate(self):
self.x=int(input("Enter xval:"))
self.y=int(input("Enter y val:"))
print(self.x*self.y)

def combine(self):#list cooncatenation


self.a=[2,3,4]
self.b=[5,6,7]
print(self.a+self.b)

#common interface
def common(obj):#obj=s1
obj.calculate()
obj.combine()

s1=sample()
s2=sample1()

common(s1)
common(s2)

================================

# comparision operator overloading

class sample:
def __init__(self,name,wt):
self.name=name
self.wt=wt

def __lt__(self,other):
return self.wt<other.wt

s1=sample("sam",56)
s2=sample("john",67)

print(s1<s2)
print(s2<s1)

#functions
'''
__add__(),__lt__(),__gt__(),__mul__(),__truediv__(),__sub__(),__floordiv__(),
__eq__(),__ne__(),__le__(),__ge__()
'''

===========================

# + operator overloading

class sample:
def __init__(self,x,y):
self.x=x
self.y=y

def __add__(self,other):
return self.x+other.x,self.y+other.y

s1=sample(5,6)
s2=sample(7,8)
s3=s1+s2
print(s3)

==========================

#generator expression

sq=(i*i for i in range(5))


#print(next(sq))
#print(next(sq))

for i in sq:
print(i)

#pipelining generators

def evennos(num):
for x in range(num):
if x%2==0:
yield x
def square(num):
for n in num:
if n%2==0:
yield n**2

print(sum(square(evennos(5))))

==========================

#iterator
#iter(),next()

x="python"
itobj=iter(x)
print(next(itobj))
print(next(itobj))
print(next(itobj))

y=[7,8,9,10]
it=iter(y)
print(next(it))
print(next(it))

===========================

def genfun(x):
for i in range(len(x)):
yield x[i]

itobj=genfun("python")
print(next(itobj))
print(next(itobj))

name=str(input("enter ur name:"))
age=int(input("enter ur age:"))
print(name,age)

print(next(itobj))

========================

#iterator
#iter(),next()

class sample:
def __init__(self,n):
self.n=n

def __iter__(self):
self.a=0
return self
def __next__(self):
if self.a<=self.n:
x=self.a
self.a+=1
return x

else:
raise StopIteration

samp=sample(5)
it=iter(samp)#it is an iterator object
print(next(it))
print(next(it))

===============================

#generator
#it is a function which will have yield stmt
#generator func creates an iterator(avoid iter())
#next()
#it remembers the previous state of the local var

def genfun():
n=1
print("first")
yield n

n+=1
print("second")
yield n

n+=1
print("third")
yield n

itobj=genfun()
print(next(itobj))
print(next(itobj))

name=str(input("enter ur name:"))
age=int(input("enter ur age:"))
print(name,age)

print(next(itobj))

=========================================

multilines=["hello\n","python\n","developers"]
f=open("C://textfiles/aravind.txt","w")
f.writelines(multilines)
f.close()

============================
#append mode
f=open("C://textfiles/aravind.txt","a")
f.write("\n hello java")
f.close()

================

#create or overwrite the text file


#open(path,mode),write()
f=open("C://textfiles/aravind1.txt","w")
f.write("hello java")
f.close()
============

f=open("C://textfiles/aravind.txt","r")
#line=f.read()
'''line1=f.readline()
print(line1)
line2=f.readline()
print(line2)'''

lines=f.readlines()
print(lines)
f.close()

==============

#decorator function

def decorfun(func):
def inner(a,b):
if b==0:
print("division not possible")
else:
func(a,b)
return inner

@decorfun
def division(a,b):
print(a/b)

division(6,3)

====================

def decorfun(func):#msg
def inner():
print("*"*6)
func()#msg()
print("*"*6)
return inner#calling the inner function

@decorfun #is carrying the normal func


def msg():
print("hello")
msg()

===================

#update operation
import mysql.connector

email=str(input("Enter the email"))


newloc=str(input("Enter the new location:"))

#mysql connection

conn=mysql.connector.connect(host="localhost",user="root",password="",database="sho
pping")

curs=conn.cursor()#it points to the database

qry="UPDATE customers SET LOCATION='%s' WHERE EMAIL='%s'" \


% (newloc,email)

curs.execute(qry)
conn.commit()

print("record updated")

===============

#delete operation
import mysql.connector

email=str(input("Enter the email"))

#mysql connection

conn=mysql.connector.connect(host="localhost",user="root",password="",database="sho
pping")

curs=conn.cursor()#it points to the database

qry="DELETE FROM customers WHERE EMAIL='%s'" % (email)

curs.execute(qry)
conn.commit()

print("record deleted")

======================

#insert operation
import mysql.connector

name=str(input("Enter the name:"))


email=str(input("Enter the email"))
loc=str(input("Enter the location:"))
#mysql connection

conn=mysql.connector.connect(host="localhost",user="root",password="",database="sho
pping")

curs=conn.cursor()#it points to the database

qry="INSERT INTO customers (FIRST_NAME,EMAIL,LOCATION) VALUES ('%s','%s','%s')" %


(name,email,loc)

curs.execute(qry)
conn.commit()

print("record inserted")

==========================

#select operation
import mysql.connector

email=str(input("Enter the email"))

#mysql connection

conn=mysql.connector.connect(host="localhost",user="root",password="",database="sho
pping")

curs=conn.cursor()#it points to the database

#qry="SELECT * FROM customers"


#qry="SELECT FIRST_NAME,EMAIL,LOCATION from customers"
qry="SELECT * FROM CUSTOMERS WHERE EMAIL='%s'" % (email)
curs.execute(qry)

print("view records")

'''res=curs.fetchall()

for x in res:
print(x)'''

res=curs.fetchone()
print(res)

print(res[4])

=================

#delete operation
import mysql.connector

rno=int(input("Enter the roll number"))

#mysql connection
conn=mysql.connector.connect(host="localhost",user="root",password="root",database=
"college")

curs=conn.cursor()#it points to the database

qry="DELETE FROM students WHERE RNO='%d'" % (rno)

curs.execute(qry)
conn.commit()

print("record deleted")

=======================

#select operation
import mysql.connector

#mysql connection

connection=mysql.connector.connect(host="localhost",user="root",password="",databas
e="banking")

class Banking:

def __init__(self,mainbal):
self.mainbal = mainbal

def get_option(self):
number = int(input("Enter 1 to deposit. Enter 2 to withdraw. Enter 3 to
transfer money:"))
if number==1:
self.deposit()
elif number == 2:
self.withdraw()
elif number ==3:
self.transfer()
else:
print("Error")

def deposit(self):
self.deposit_amount = int(input("Enter deposit amount"))
if self.deposit_amount > 25000:
self.mainbal = self.mainbal + 0.98 * self.deposit_amount
else:
self.mainbal = self.mainbal + self.deposit_amount
print("Main Balance:",self.mainbal)

def withdraw(self):
self.with_amount = int(input("Enter withdrawal amount"))
if self.mainbal > self.with_amount:
self.mainbal = self.mainbal - self.with_amount
print("Main Balance:",self.mainbal)
else:
print("Insufficient funds, try again")

def transfer(self):
self.transfer_account = int(input("Enter the account ID number"))
self.transfer_amount = int(input("Enter the transfer amount"))
try:
if self.mainbal > self.transfer_amount:
self.mainbal = self.mainbal - self.transfer_amount
print("Main Balance:",self.mainbal)
sql_select_Query = "select * from customer"
cursor = connection.cursor()
cursor.execute(sql_select_Query)
# get all records
records = cursor.fetchall()
total_amount = self.transfer_amount +
records[ self.transfer_account-1][4]
sql_update_query = """Update customer set AMOUNT = %d where id =
%d""" \
%(total_amount,self.transfer_account)
cursor.execute(sql_update_query)
connection.commit()

else:
print("Insufficient funds")
except:
print("Invalid User ID, please try again")

sql_select_Query = "select * from customer"


cursor = connection.cursor()
cursor.execute(sql_select_Query)
# get all records
records = cursor.fetchall()

q="wrong"
while q=="wrong":
try:
user_id = int(input("Enter your account id:"))
user_name = str(input("Enter your user name:"))
password = int(input("Enter your password:"))
if user_name == records[user_id-1][2] and password == records[user_id-1]
[3]:
print("Hello {}, Welcome to Digital Bank of Python
(DBP).".format(records[user_id-1][1]))
print("Your main balance is {}.".format(records[user_id-1][4]))
q="correct"
else:
print("Invalid credentials, try again")
except:
print("incorrect user_id")

x= records[user_id-1][4]
obj = Banking(x)
p = "yes"
while p=="yes":
obj.get_option()
final_amount=(obj.mainbal)
p = str(input("Want to continue? yes/no"))

cursor=connection.cursor()
sql_update_query = """Update customer set AMOUNT = %d where id = %d""" \
%(final_amount,user_id)
cursor.execute(sql_update_query)
connection.commit()

print("Thanks for banking with us. Have a niceday. Your final amount is
{}".format(final_amount))

========================================================================

'''
1.Python program to extract and print digits in reverse order of a number
i/p:1234
'''
class reverse:
def numbera_rev(self,number):
self.num = number
self.result = str(self.num)[::-1]
return self.result

obj = reverse()
print(obj.numbera_rev(123))

'''
2.Write functions to find square and cube of a given number.
'''
class calc:
def sq_cube(self,num):
self.sq=num**2
self.cube = num**3
print("square:{} cube:{}".format(self.sq,self.cube))

obj2 = calc()
obj2.sq_cube(12)

'''
3.Find the sum of all numbers below 100 which are multiples of 3 or 5 in
Python
'''

class multiples_3_5:
def __init__(self):
self.sum = 0
for i in range(100):
if i%3==0 and i%5==0:
self.sum+=i
print(self.sum)

obj3 = multiples_3_5()
obj3

'''
4.Lambda function to return the grade of the students of a class. The marks of all
students are stored in an array. And we will use the for in loop to access each
value of the array.
studentMarks = [56,77,88,45,2,27,44]
Output:

['Second', 'First', 'First', 'Second', 'Fail', 'Fail', 'Fail']


'''

class Marks:
def grade(self,marks):
self.grade = []
for i in marks:
p=lambda x:"first" if x>75 else ("second" if x>=45 else "fail")
self.grade.append(p(i))
return self.grade

studentMarks = [56,77,88,45,2,27,44]
obj4 = Marks()
print(obj4.grade(studentMarks))

'''
5.Input:
text = "this is a book, this is very popular"
word = "this"

Output:
'this' found 2 times.
'''

class Counting:
def text_count(self,text,word):
x=text.count(word)
print("{} found {} times.".format(word,x))

text = "this is a book, this is very popular"


word = "this"
obj5 = Counting()
obj5.text_count(text,word)

'''
6.Integer Input Validation with Exception Handling (Example of ValueError
Exception) in Python
'''
try:
a=int(input("Enter a number"))
b= int(input("Enter another number"))
except ValueError:
print("String not allowed")
else:
print("{} is first number. {} is second number".format(a,b))
finally:
print("end")
'''
7.Python program to raise an exception
'''

x=int(input("Enter a positive integer"))


y=int(input("Enter a negative integer"))

if not type(x) and not type(y) is int:


raise TypeError("Must be integer")
if x<0 or y>0:
raise Exception("Incorrect values, follow instruction")
else:
print(x+y)

'''
8.Read contents of the file using readlines() method also append content in Python
'''

f = open("test_q8.txt", "r")
lines = f.readlines()
print(lines)
f.close()

f = open("test_q8.txt", "a")
f.write("\n design a game in pycharm")
f.close()

f = open("test_q8.txt", "r")
lines = f.readlines()
print(lines)
f.close()

'''
9.Example to implement destructor and constructors using __del__() and __init__()
'''
class Person:
def __init__(self, name, age):
self.time = name
self.age = age
print(self.time*self.age)

def __del__(self):
print('__del__ was called')

for i in range(1,5):
person = Person(i,23)

'''
10.Illustrate the working of decorators and generators.
'''

#converts decimal to binary


def decorfun(func):
def inner(a):
count=0
b="10"
for val in str(a):
if val not in b:
count = 1
if count==1:
print("binary conversion not possible")
else:
func(a)
return inner

@decorfun
def division(a):
decimal, i = 0, 0
while(a != 0):
dec = a % 10
decimal = decimal + dec * pow(2, i)
a = a//10
i += 1
print("Decimal value is:", decimal)

division(10101)

#pipelining generators
def fibonacci_numbers(nums):
x, y = 0, 1
for i in range(nums):
x, y = y, x+y
yield x

def square(nums):
for num in nums:
yield num**0.5

print(sum(square(fibonacci_numbers(10))))

You might also like