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

Python Output

The document demonstrates different Python exceptions using try-except blocks. It prompts the user to enter a number between 1 to 5. For each number, it runs a code block that is designed to trigger a specific exception: 1) ZeroDivisionError for division by zero, 2) ValueError for non-numeric input, 3) NameError for undefined variable. Each exception block prints an error message, while the else block prints the result if no exception occurs. This allows the user to see different exceptions being handled with try-except statements in Python.

Uploaded by

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

Python Output

The document demonstrates different Python exceptions using try-except blocks. It prompts the user to enter a number between 1 to 5. For each number, it runs a code block that is designed to trigger a specific exception: 1) ZeroDivisionError for division by zero, 2) ValueError for non-numeric input, 3) NameError for undefined variable. Each exception block prints an error message, while the else block prints the result if no exception occurs. This allows the user to see different exceptions being handled with try-except statements in Python.

Uploaded by

Shubham Bhalekar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Experiment No:-01

Program:-
print("---------------COMMENTS-----------------")
print('Single Line "#"')
print('Multi Line ("""---""")')
print("Multi Line ('''---''')")
print("")
print("--Datatypes,Expressions,Output Statement & Conversions-")
a=16 #int datatype
a1="abc" #string datatype
b=23.32 #Float datatype
c=2.3+3.2j #Complex datatype
d=1.2-2.8j #Complex datatype
e=c+d #expression
e1=a*b #expression
print("Sum is",e) #Output statement
print('Multiplication is ', e1) #Output statement
f=float(a) #Converting int to float
print('Int to Float', f)
g=complex(b) #Converting float to complex
print('Float to Complex', g)
h=oct(a) #Decimal to octal
print('Decimal to Octal', h)
i=bin(a) #Decimal to binary
print('Decimal to Binary', i)
j=hex(a) #Decimal to hexadecimal
print('Decimal to Hexadecimal',j)
print ("")
print("------INPUT STATEMENT---------")
k=input('What is your name? using raw input ') #ask & returns string of dat
a
print('Your name is ' + k)
l=input('Enter value of x ')
print('Entered value of x using String Function is ' + str(l)) #Printing Ou
tput in String Format
print('Entered value of x using format function is {0}'.format(l)) #Printin
g Formatted Output
print("accept integer input",int(input())) #Accept Integer Input
print("")
print("-------Knowing the datatype------")
a=12
print(type(a))
b="str"
print(type(b))
c=1.2+4j
print(type(c))
Output:-
Experiment No:-02
Program:-
#@title Default title text
#Demonstrating
print("---------------BYTEARRAY FUNCTIONS-----------------")
print("")
x=[10,20,30,40,50] #Creating integer List
print("Creating a bytearray using bytearray function")
x1=bytearray(x) #Converting List in to Bytearray
print("printing bytearray:")
print(x[0],x[1],x[2],x[3],x[4]) #printing Bytearray
print("")
print("--------RANGE DATATYPE ------------")
print("")
r=range(1,9) #Creating a range of 1 to 9 elements
print("range of 1 to 9 is :",r)
r=range(10) #Creating a range first 10 elements
print("range of 10 is :",r)
print("")
print("--SET DATATYPE (Unordered elements with no duplicate)--")
print("")
s={1,4,6,3} #Creating a set
print(s) #Printing set in ascending order
c1=set("BHUSHANA") #Creating a character set
print(c1) #Printing set alphabetically and avoiding duplication of Char
acter
s.update([4,5]) #Adding element 5 after 4 in set s
print(s) #Printing set in ascending order
fs=frozenset(s) #Creating a frozen of set s i.e. Fixed Set cant be modi
fied
print(fs)
print("")
print("---------------STRING -----------------")
print("")
str="""WELCOME TO 'CORE PYTHON PROGRAMMING' COURSE""" #STRING Datatype
print("printing String array:")
print(str)
print("Printing first four element of String Array:") #Printing first f
our element of String Array
#FIRST POSITION WILL BE A SPACE SO PRINT ACCORDINGLY
print(str[0:4])
print("Printing first character from end:") #Printing first character f
rom end
print(str[-1])
print("Printing nineth character of String Array:") #Printing nineth ch
aracter
print(str[8])
print("")
print("---------------STRING FUNCTIONS-----------------")
print("")
s1="CORE PYTHON PROGRAMMING"
s2="IS BEST"
print("Length:", len(s1)) #Printing length
print("Repeate twice:",(s1)*2) #Repeat string
print("Concat : specified Character in the strings:",s1.count('M'))
#Counting
a1='CORE'
a2='BEST'
print("Replacing CORE with BEST:", s1.replace(a1,a2))
print("Changing case from uppercase to Lower:", s1.lower())
print("SORTING STRINGS:", sorted(s2))
s4=u'\u0915\u0947\u0964\u0930 \u092a\u0948\u0925\u0964\u0928'
#String with unicode
print("UNICODE FOR CORE PYTHON", s4)

Output:-
Experiment No:-03
Program:-

from array import * #Import an array package
print ("---------------LIST -----------------")
print ("")
l=[12,23,-5,0.8,'python',"BJ"] #Creating a list of variable datatypes
print ("printing original list",l) #printing list
print ("printing first three elements of a list", l[0:3] )#printing first three ele
ments of a list
print ("printing Last elements of a list",l[-1]) #printing Last elements of a list
print ("printing first three elements of a list twice",l[0:3] * 2) #printing first 
three elements of a list twice
print ("")
print ("---------------LIST FUNCTIONS-----------------")
print ("")
l1=list(range(1,8)) #Creating a list of range 1 to 7
print ("List of range 1 to 7", l1)
l1.append(9) #append 9
print ("Append 9 :",l1)
l1.sort(reverse=True)
print ("Descending Sort:",l1)
l1.sort()
print ("Ascending Sort:",l1)
l1.reverse()
print ("Reverse:",l1)
l1.sort()
l1.remove(9)
print ("Remove 9:",l1)
print ("count:",l1.count(5))
print ("max:",max(l1))
print ("min:",min(l1))
print ("Index of 6:",l1.index(6))
print ("--------MATRICES using LIST---------------")
print ("")
m1=[1,2,3],[4,5,6],[7,8,9]
for r in m1:
  print(r)
print ("")
print ("--------TUPLE DATATYPE (READ ONLY LIST)------------")
print ("")
tpl=(-5,0.8,'python',"BJ") #Creating a Tuple
print ("Created Tuple is ", tpl)
print ("Tuple elements 0 to 2 is", tpl[0:2]) #printing first two elements of a tupl
e
print ("Tuple element -2 is ", tpl[-2]) #printing Second last elements of a tuple
print ("")
print ("--------TUPLE FUNCTIONS -----------")
tpl2=(10,20,30,40,10,20,10) #Creating a Tuple2
print ("Created Tuple2 is ", tpl2)
print ("Length : ", len(tpl2))
print ("Min : ", min(tpl2))
print ("Max : ", max(tpl2))
print ("Count no. of 10's: ", tpl2.count(10))
print ("Reverse Sort : ", sorted(tpl2,reverse=True))
print ("")
print ("--------DICTIONARIES i.e. key:value pair------------")
print ("")
d1={'Name':"bhushan",'gender':"M",'age':32,'college':"tsec"} #create dictionary
print ("print dictionary: ",d1)
print ("")
print ("-->Keys :",d1.keys())
print ("-->Values :",d1.values())
print ("-->Keys and values :",d1.items())
d1.update({'country':"india"})
print ("-->Print updated dictionary: ",d1)
c=sorted(d1.items(),key=lambda t:t[1])
print ("-->Sort By values :",c)
print ("---------------ARRAYS -----------------")
print ("")
arr=array('i',[10,20,30,40,50]) #Create array with integer values
print ("The Array Elements are")
for i in arr: #i is element and arr in array name
  print (i) #Requires indentation
print ("length of array is",len(arr))
arr1=array('c',['a','b','c','d']) #Create array with character values
print ("The Character Array Elements are")
for ch in arr1: #i is element and arr1 in array name
  print (ch) #Requires indentation
Output:-
Experiment N0:-04
Program:-
print("--Finding MAX BETWEEN 3 Nos using IF-Else-Elif STATEMENT--")
a=input("Enter value of First element:")
b=input("Enter value of Second element:")
c=input("Enter value of Third element:")
if a>b and a>c:
  print(a,"is Greater")
elif b>c:
  print(b,"is Greater")
else:
  print(c,"is Greater")
print("")
print("-----Calculate Factorial using WHILE LOOP-----------")
num=int(input("Enter the number : "))
fact=1
i=1
while i <= num:
  fact=fact*i
  i=i+1
  print("Factorial of",num," is :",fact)
print("-----Generate Fibonacci series using If statement & WHILE LOOP-----------")
n=int(input("How many numbers??? : "))
f1=0
f2=1
c=2
if n==1:
  print(f1)
elif n==2:
  print(f1,'\n',f2)
else:
  print(f1,'\n',f2)
while c<n:
  f=f1+f2
  print(f)
  f1,f2=f2,f
  c+=1
Output:-
Experiment No:- 05
Program:-

#FOR LOOP
print("--Multiplication table using FOR loop--")
n=int(input("Enter the number:"))
for i in range(1,11):
  print(n,"X",i,"=",n*i)
print("")
print("--Pascal triangles--")
n=int(input("Enter the rows:"))
trow=[1]
y=[0]
for x in range(max(n,0)):
  print(trow)
  trow=[l+r for l,r in zip(trow+y, y+trow)]
  n>=1

Output:-
Experiment N0:-06
Program:-
def my_function(fname):
  print(fname + "Welcome to PVPPCOE")
my_function("Shubham")
def my_function(fname,lname):
    print(fname +""+lname)
my_function("Shubham","Bhalekar")

def my_function2(*fruits):
      print("The Favourite Fruit is"+ fruits[2])
my_function2("Apple","Banana","Mango","Guava","Custarapple")

def my_functionf(food):
       for x in food:
        print(x)
snacks = ["Vadapav","Samosa","Dosa","Idli"]
my_functionf(snacks)

def my_square(x):
        return x * x
print("42 square ;",my_square(42))
print("99 square ;",my_square(99))

Output:-
Experiment N0:-07
Program:-
#Demonstrate Class object static method and inner class
class Student:
  roll=int(input('Enter your Roll Number \n'))
  name=input('Enter your Name \n')
  age=int(input('Enter your Age \n'))
  gender=input('Enter your Gender \n')
  print("")
  class address: #Inner Class
    print("-------------Inner Class--------------")
    print("This is Inner class")
  @staticmethod #Static method
  def statmeth():
    print("This is Static method")
  def display_record(self):
    print("Your Roll number is",self.roll)
    print("Your Name is",self.name)
    print("Your Age is",self.age)
    print("Your Gender is",self.gender)
    print("")
s=Student() #Main class object
print("")
print("-------------Static Method--------------")
s.statmeth() #calling static method
print("")
print("-------------Details of Student are--------------")
s.display_record() #Calling class method

Output:-
Experiment No:-08
Program:-
i=1
while i<=5:
 n=int(input("Please enter numbers between 1 to 5 to see diffrent Exception
s : ")) 
 if n==1:
  try:
   a=int(input("Please enter number a : ")) 
   b=int(input("Please enter number b (put b=0): ")) 
   c=a/b
  except ZeroDivisionError:
   print("Oops! Number Divisible by Zero Exception Occurs.") 
  else:
   print("Division is",c) 
 elif n==2:
  try:
   a=int(input("Please enter number a : ")) 
   b=int(input("Please enter number b (put b='a'): ")) 
   c=a/b
  except ValueError:
   print("Oops! Value Error Exception Occurs.Please enter a valid number.")
  else:
   print ("Division is",c)
 elif n==3:
  try:
   a=int(input("Please enter number a : ")) 
   b=int(input("Please enter number b : ")) 
   c=k/b
  except NameError:
   print("Oops! Name Error Exception Occurs due to c=k/b (k is not defined 
).Please enter a valid variable number.")
 elif n==4:
  try:
   r='2'+2
  except TypeError:
   print("Oops! Type Error Exception Occurs (due to '2'+2).Please Provide V
alid data type. ")

 elif n==5:
  try:
   n=int(input("Please enter Numbers between 2 to 3: (Check for other nos) 
")) 
   assert n>=2 and n<=3
   print("The Number Entered is",n) 
  except AssertionError:
   print("Oops! Assertion Error Occurs..Please enter number between 2 to 5.
")
  else:
   print ("Existing The Program")
exit()
Output:-
Experiment No:-09
Create :-Program code:-
importmysql.connector testdb =
mysql.connector.connect( host="localhost
", user="root", password="root",
database="testdb")
mycursor=testdb.cursor()
mycursor.execute("Create table
customers(name varchar(20), address
varchar(20), id int(20))") print("Table
created successfully")

Output:-

Read/fetching :-Program code:-

importmysql.connector mydb = mysql.connector.connect(


host="localhost", user="root",
password="root",
database="testdb" )
mycursor = mydb.cursor() mycursor.execute("SELECT
* FROM customers") myresult =
mycursor.fetchall() for
x in myresult:
print(x)

Output:-

Update:-Program code:-

importmysql.connector mydb = mysql.connector.connect(


host="localhost", user="root",
password="root",
database="testdb"
)
mycursor = mydb.cursor() sql = "UPDATE customers SET name = 'Samuel' WHERE name =
'sam'" mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record(s)
affected") mycursor.execute("SELECT
* FROM customers") myresult =
mycursor.fetchall() for
x in myresult:
print(x)

Output:-
Delete:-Program code:-

importmysql.connector mydb = mysql.connector.connect(


host="localhost", user="root",
password="root",
database="testdb"
)
mycursor = mydb.cursor() sql = "DELETE FROM
customers WHERE id = 4"
mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record(s) deleted")
mycursor.execute("SELECT
* FROM customers") myresult =
mycursor.fetchall() for
x in myresult:
print(x)

Output:-
Experiment No:-10
Program:-

from tkinter import *


top = Tk()
top.geometry("400x400") c = Canvas(top,bg = "blue",height =

"600",width ="600") points = [170, 100, 200, 120, 240, 180,210,

200, 170, 170, 100, 200]

c.create_polygon(points, outline = "white",fill = "red", width = 2)


c.create_arc((15,10,150,200),start = 0,extent = 150, fill= "orange" , outline = "red")
c.create_oval(250, 250, 310, 310,outline = "black", fill = "maroon",width = 2)
c.create_rectangle(330, 10, 390, 60, outline = "mediumvioletred", fill = "crimson",width = 2) p

= [350,390, 270,350, 370,310]

c.create_polygon(p, fill='moccasin',outline="yellow")
c.pack() top.mainloop()

Output:-
Program:-

from tkinter import * root = Tk()


root.geometry("450x350")
w = Label(root, text ='Click to change color of buttons', font = "50") w.pack() frame =
Frame(root) frame.pack() bottomframe = Frame(root) bottomframe.pack( side =
BOTTOM )
leftframe = Frame(root) leftframe.pack( side =
LEFT ) rightframe = Frame(root)
rightframe.pack( side = RIGHT ) topframe =
Frame(root) topframe.pack()
b1_button = Button(topframe, text ="red", fg ="red",bg='#FFFFFF',
activebackground='#FF0000') b1_button.pack()
b2_button = Button(rightframe, text ="yellow", fg ="yellow",bg='#FFFFFF',
activebackground='#FFFF00') b2_button.pack( side = RIGHT )
b3_button = Button(leftframe, text ="blue", fg ="blue",bg='#FFFFFF',
activebackground='#0000FF') b3_button.pack( side = LEFT )
b4_button = Button(bottomframe, text ="green", fg ="green",bg='#FFFFFF',
activebackground='#00ff00') b4_button.pack( side = BOTTOM)
root.mainloop()

Output:-
Experiment No:-11
Program:-
import functools
"---Lambda function---"
print ("Lambda function")
f=lambda x,y:x+y
print (f(1,1))
print ("")

"---Map function---"
print ("Map function")
def fahrenheit(T):
    return((float(9)/5)*T+32)
def celsius(T):
    return (float(5)/9)*(T-32)
temp=(36.5,37,37.5,39)
F=map(fahrenheit, temp)
C=map(celsius,F)
print (F)
print (C)
print ("")

"---Reduce function---"
print ("Reduce function")
print (functools.reduce(lambda x,y:x+y,[1,2,3,4])) 
print ("")

"---Fliter function---"
print ("Filter Function")
fib=[0,1,1,2,3,5,8,13,21,34,55]
result=filter(lambda x:x %2,fib)
print (result)
print ("")

"---Range Function---"
print ("Range Function")
print (range(10))

Output:-
Experiment No:-12

TCP Server Program code:-


importsocketserver classHandler_TCPServer(socketserver.BaseRequestHandler): def handle(self):
self.data = self.request.recv(1024).strip() print("{}
sent:".format(self.client_address[0])) print(self.data)
self.request.sendall("ACK from TCP Server".encode()) if __name__ ==
"__main__": HOST, PORT =
"localhost", 9999 tcp_server = socketserver.TCPServer((HOST, PORT), Handler_TCPServer)
tcp_server.serve_forever()

Output:-

TCP Client Program code:-


import socket host_ip, server_port = "127.0.0.1", 9999 data = " Hello how are you?\n"
tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try:
tcp_client.connect((host_ip, server_port))
tcp_client.sendall(data.encode()) received =
tcp_client.recv(1024) finally: tcp_client.close() print ("Bytes
Sent: {}".format(data)) print ("Bytes Received:
{}".format(received.decode()))

Output:-

You might also like