Advertisement
zoro-10

Python Practicals

Oct 15th, 2023 (edited)
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 17.79 KB | None | 0 0
  1. # --------------------------------------------------------------------------------------------------------------------------------------
  2. # Practical 1A
  3. # Create a program that ask the user to enter their name and their age. Print out a message addressed to
  4. # them that tells them the year that they will turn 100 year old.
  5.  
  6.  
  7. import operator
  8. name = input("Whats your name::")
  9. age = int(input("how old you are::"))
  10. year = str((2017-age)+100)
  11. print(name+" you will be 100 year old in the year::"+year)
  12.  
  13. # --------------------------------------------------------------------------------------------------------------------------------------
  14.  
  15. # Practical 1B
  16. # Enter the number from user and depending on whether the number is even or odd, print out an
  17. # approrpriate message to the user.
  18.  
  19.  
  20. a = int(input("Enter any number::"))
  21. if a % 2 == 0:
  22.     print("It's even number")
  23. else:
  24.     print("It's odd number")
  25.  
  26. # --------------------------------------------------------------------------------------------------------------------------------------
  27.  
  28.  
  29. # Practical 1C
  30. # Write a program to generate the fibonacci series.
  31.  
  32.  
  33. v = int(input("\n Please enter the range number: "))
  34. a = 0
  35. b = 1
  36. for n in range(0, v):
  37.     if (n <= 1):
  38.         c = n
  39.     else:
  40.         c = a+b
  41.         a = b
  42.         b = c
  43.     print(c)
  44.  
  45.  
  46. # --------------------------------------------------------------------------------------------------------------------------------------
  47.  
  48.  
  49. # Practical 1D
  50. # Write a function that reverses the user defined value.
  51.  
  52.  
  53. def rev(num):
  54.     a = 0
  55.     while (num > 0):
  56.         b = num % 10
  57.         a = (a*10)+b
  58.         num = num//10
  59.     print("reverse number is::", a)
  60.  
  61.  
  62. a = int(input("Enter any number::"))
  63. rev(a)
  64.  
  65.  
  66. # --------------------------------------------------------------------------------------------------------------------------------------
  67.  
  68.  
  69. # Practical 1E
  70. #: Write a function to check the input value is Armstrong and also write the function for Palindrome
  71.  
  72. def armstrong(num):
  73.     sum = 0
  74.     temp = num
  75.     while temp > 0:
  76.         digit = temp % 10
  77.         sum += digit**3
  78.         temp //= 10
  79.     if num == sum:
  80.         print(num, "is an armstrong number")
  81.     else:
  82.         print(num, "is not an armstrong number")
  83.  
  84.  
  85. def palindrome(num):
  86.     n = num
  87.     rev = 0
  88.     while num != 0:
  89.         rev = rev*10
  90.         rev = rev+int(num % 10)
  91.         num = int(num/10)
  92.     if n == rev:
  93.         print(n, "is palindrome number")
  94.     else:
  95.         print(n, "is not a palindrome number")
  96.  
  97.  
  98. num = int(input("Enter a number to check it is armstrong or not: "))
  99. armstrong(num)
  100. num = int(input("Enter a number to check it is palindrome or not: "))
  101. palindrome(num)
  102.  
  103.  
  104. # --------------------------------------------------------------------------------------------------------------------------------------
  105.  
  106.  
  107. # Practical 1F
  108. # Write a recursive function to print the factorial for a given number.
  109.  
  110. def factorial(n):
  111.     if n == 1:
  112.         return 1
  113.     else:
  114.         return n*factorial(n-1)
  115.  
  116.  
  117. n = int(input('Enter a number::'))
  118. fact = factorial(n)
  119. print('factorial of', n, 'is', fact)
  120.  
  121. # --------------------------------------------------------------------------------------------------------------------------------------
  122.  
  123.  
  124. # Practical 2A
  125. # :Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False
  126. # otherwise.
  127.  
  128.  
  129. def find_vowel(s):
  130.  l=['a','e','i','o','u','A','E','I','O','U']
  131.  for i in s:
  132.  if i in l:
  133.  print("True")
  134.  else:
  135.  print("False")
  136. s=input("Enter any word to check it vowel or not::")
  137. find_vowel(s)
  138.  
  139.  
  140. # --------------------------------------------------------------------------------------------------------------------------------------
  141.  
  142.  
  143. # Practical 2B
  144. # Define a function that computes the length of a given list or string
  145.  
  146.  
  147. def len_s(s):
  148.     count = 0
  149.     for i in s:
  150.         if i != '':
  151.             count += 1
  152.     print('The total length of string:', count)
  153.  
  154.  
  155. s = input("Enter a string to check the length of it::")
  156. len_s(s)
  157.  
  158.  
  159. # --------------------------------------------------------------------------------------------------------------------------------------
  160.  
  161.  
  162. # Practical 2C
  163. # Define a procedure histogram() that takes a list of integers and prints a histogram to the screen. For
  164. # example, histogram([4, 9, 7]) should print the following
  165.  
  166.  
  167. def histogram(items):
  168.     for n in items:
  169.         output = ' '
  170.         times = n
  171.         while (times > 0):
  172.             output += '*'
  173.             times = times-1
  174.         print(output)
  175.  
  176.  
  177. histogram([4, 9, 7])
  178.  
  179.  
  180. # --------------------------------------------------------------------------------------------------------------------------------------
  181.  
  182.  
  183. # Practical 3A
  184. # A pangram is a sentence that contains all the letters of the English alphabet at least once, for example:
  185. # The quick brown fox jumps over the lazy dog. Your task here is to write a function to check a sentence to
  186. # see if it is a pangram or not.
  187.  
  188.  
  189. import string
  190. def ispangram(sentence,alphabet=string.ascii_lowercase):
  191.  aset=set(alphabet)  
  192.  return aset<=set(sentence.lower())
  193. print(ispangram(input("Enter the sentence:")))
  194.  
  195.  
  196. # --------------------------------------------------------------------------------------------------------------------------------------
  197.  
  198.  
  199. # Practical 3B
  200. # Take a list, say for example this one.
  201.  
  202. a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  203. for i in a:
  204.     if i < 5:
  205.         print(i)
  206.  
  207.  
  208. # --------------------------------------------------------------------------------------------------------------------------------------
  209.  
  210.  
  211. # Practical 4A
  212. # Write a program that takes two lists and returns True if they have at least one common member
  213.  
  214.  
  215. list1 = [1, 2, 3, 4, 5, 6]
  216. list2 = [11, 12, 13, 14, 15, 6]
  217. for i in list1:
  218.     for j in list2:
  219.         if i == j:
  220.             print('TRUE...The two list have at least one common element')
  221.  
  222.  
  223. # --------------------------------------------------------------------------------------------------------------------------------------
  224.  
  225.  
  226. # Practical 4B
  227. # Write a Python program to print a specified list after removing the 0th, 2nd, 4th and 5th elements.
  228.  
  229. list = [1, 2, 3, 4, 5, 6, 7, 8]
  230. list = [x for (i, x) in enumerate(list) if i not in (0, 2, 4, 5)]
  231. print(list)
  232.  
  233.  
  234. # --------------------------------------------------------------------------------------------------------------------------------------
  235.  
  236.  
  237. # Practical 4C
  238. # Write a Python program to clone or copy a list
  239.  
  240.  
  241. list1 = [1, 2, 3, 4, 5]
  242. n = list(list1)
  243. print("list2=", n)
  244.  
  245.  
  246. # --------------------------------------------------------------------------------------------------------------------------------------
  247.  
  248.  
  249. # Practical 5A
  250. # Write a Python script to sort (ascending and descending) a dictionary by value
  251.  
  252.  
  253. dic = {'a1': 12, 'a3': 14, 'a4': 13, 'a2': 11, 'a0': 10}
  254. print('Original dictionary:', dic)
  255. ascending = sorted(dic.items(), key=operator.itemgetter(0))
  256. descending = sorted(dic.items(), key=operator.itemgetter(0), reverse=True)
  257. print('Ascending order:', ascending)
  258. print('Descending order:', descending)
  259.  
  260.  
  261. # --------------------------------------------------------------------------------------------------------------------------------------
  262.  
  263.  
  264. # Practical 5B
  265. # Write a Python script to concatenate following dictionaries to create a new one. Sample Dictionary
  266.  
  267.  
  268. dic1 = {1: 10, 2: 20}
  269. dic2 = {3: 30, 4: 40}
  270. dic3 = {5: 50, 6: 60}
  271. dic4 = {}
  272. for d in (dic1, dic2, dic3):
  273.     dic4.update(d)
  274. print(dic4)
  275.  
  276.  
  277. # --------------------------------------------------------------------------------------------------------------------------------------
  278.  
  279.  
  280. # Practical 5C
  281. # Write a Python program to sum all the items in a dictionary.
  282.  
  283. dict = {"key1": 5, "key2": 3, "key3": 7}
  284. print("Dictionary items")
  285. print(dict.values())
  286. print("Sum of dictionary values:", sum(dict.values()))
  287.  
  288.  
  289. # --------------------------------------------------------------------------------------------------------------------------------------
  290.  
  291.  
  292. # Practical 6A
  293. # Write a python program to read an entire text file #Contents of TextRead.txt File This is a text file
  294. # which will be read by this program and will display on screen
  295.  
  296.  
  297. # make dummy.txt and paste Hello Everyone and then save
  298.  
  299.  
  300. # code:
  301.  
  302. f = open('dummy.txt', 'w+')
  303. f.write("Hello Everyone")
  304. f.seek(0)
  305. t = f.read()
  306. print(t)
  307. f.close()
  308.  
  309.  
  310. # --------------------------------------------------------------------------------------------------------------------------------------
  311.  
  312.  
  313. # Practical 6B
  314. # Write a Python program to append text to a file and display the text
  315.  
  316.  
  317. # TextRead.txt:
  318. '''
  319. First Line added to the file
  320. Second Line added to the file
  321. Third Line added to the file
  322. '''
  323.  
  324.  
  325. # code:
  326.  
  327. with open("TextRead.txt", "a+")as file:
  328.     file.write("\n Second Line added to the file")
  329.     file.write("\n Third Line added to the file")
  330. text = open("TextRead.txt")
  331. print(text.read())
  332.  
  333.  
  334. # --------------------------------------------------------------------------------------------------------------------------------------
  335.  
  336.  
  337. # Practical 6C
  338. # Write a Python program to read last n lines of a file.
  339.  
  340.  
  341. f = open('TextRead.txt', 'r')
  342. s = f.readlines()
  343. print(s[1])
  344. f.close()
  345.  
  346.  
  347. # --------------------------------------------------------------------------------------------------------------------------------------
  348.  
  349.  
  350. # Practical 7A
  351. # Design a class that store the information of student and display the same.
  352.  
  353.  
  354. class student:
  355.     def __init__(self, name, address, mobile, email):
  356.         self.name = name
  357.         self.address = address
  358.         self.mobile = mobile
  359.         self.email = email
  360.  
  361.     def display(self):
  362.         print("Name:", name)
  363.         print("Address:", address)
  364.         print("Mobile:", mobile)
  365.         print("Email:", email)
  366.  
  367.  
  368. print("Enter your details:")
  369. name = input("Enter your name:")
  370. address = input("Enter your address:")
  371. mobile = input("Enter your mobile:")
  372. email = input("Enter your Email:")
  373. s = student(name, address, mobile, email)
  374. s.display()
  375.  
  376.  
  377. # --------------------------------------------------------------------------------------------------------------------------------------
  378.  
  379.  
  380. # Practical 7B
  381. # Implement the concept of inheritance using python.
  382.  
  383.  
  384. class st:
  385.     def s1(self):
  386.         print("base class")
  387.  
  388.  
  389. class st1(st):
  390.     def s2(self):
  391.         print("derived class")
  392.  
  393.  
  394. t = st1()
  395. t.s1()
  396. t.s2()
  397.  
  398.  
  399. # --------------------------------------------------------------------------------------------------------------------------------------
  400.  
  401.  
  402. # Practical 7C
  403. # Create a class called Numbers, which has a single class attribute called MULTIPLIER, and a constructor
  404. # which takes the parameters x and y (these should all be numbers).
  405. # i. Write a method called add which returns the sum of the attributes x and y.
  406. # ii. Write a class method called multiply, which takes a single number parameter a and returns the product of
  407. # a and MULTIPLIER.
  408. # iii. Write a static method called subtract, which takes two number parameters, b and c, and returns b-c.
  409. # iv. Write a method called value which returns a tuple containing the values of x and y. Make this method
  410. # into a property, and write a setter and a deleter for manipulating the values of x and y
  411.  
  412.  
  413. class Number:
  414.     Multiplier = 10
  415.  
  416.     def __init__(self, x, y):
  417.         self.x = x
  418.         self.y = y
  419.  
  420.     def add(self):
  421.         return (self.x+self.y)
  422.  
  423.     @classmethod
  424.     def multiply(cls, a):
  425.         return (cls.Multiplier*a)
  426.  
  427.     @staticmethod
  428.     def sub(b, c):
  429.         return (b-c)
  430.  
  431.     @property
  432.     def value(self):
  433.         return (self.x, self.y)
  434.  
  435.     def s_value(self, x, y):
  436.         self.x = x
  437.         self.y = y
  438.  
  439.     def d_value(self):
  440.         del self.x
  441.         del self.y
  442.  
  443.  
  444. N = Number(20, 30)
  445. N = Number(20, 30)
  446. 24
  447. print("Addition=", N.add())
  448. print("Multiplication=", N.multiply(5))
  449. print("Subtraction=", Number.sub(9, 6))
  450. print("Property value=", N.value)
  451. print("Set value=", N.s_value(4, 3))
  452. print("Property value=", N.value)
  453. print("Deleted value=", N.d_value())
  454.  
  455.  
  456. # --------------------------------------------------------------------------------------------------------------------------------------
  457.  
  458.  
  459. # Practical 8A
  460. # Open a new file in IDLE (“New Window” in the “File” menu) and save it as geometry.py in the
  461. # dictionary where you keep the files you create for this course. Then copy the functions you wrote for
  462. # calculating volumes and areas in the “Conrol Flow and Functions” exercise into this file and save it.
  463. # Now open a new file and save it in the same directory. You should now be able to import geometry
  464. # Try and add priny dir(geometry) to the file and run it.
  465. # Now write a function pointyShapeVolume(x,y,squareBase) that calculates the volume of a square pyramid if
  466. # squareBase is True and of a right circularcone if squareBase is False. X is the length of an edge on a square
  467. # if squareBase is True and the radius of a circle when squareBase is False.y is the height of the object.First
  468. # use squareBase to distinguish the cases. Use the cicleArea and squareArea from the geometry module to
  469. # calculate the base areas.
  470.  
  471.  
  472. # make 2 files
  473. # 1. geometry.py:
  474.  
  475.  
  476. def sphereArea(r):
  477.     return 4*math.pi*r**2
  478.  
  479.  
  480. def sphereVolume(r):
  481.     return 4*math.pi*r**3/3
  482.  
  483.  
  484. def spherematrices(r):
  485.     return sphereArea(r), sphereVolume(r)
  486.  
  487.  
  488. def circleArea(r):
  489.     return math.pi*r**2
  490.  
  491.  
  492. def squareArea(x):
  493.     return x**2
  494.  
  495. # 2. demo.py (run this file only)
  496.  
  497.  
  498. def pointyShapeVolume(x, y, squareBase):
  499.     if squareBase == True:
  500.         print("Square area:", geometry.squareArea(x))
  501.     else:
  502.         print("Circle area:", geometry.circleArea(x))
  503.  
  504.  
  505. print(dir(geometry))
  506. pointyShapeVolume(2, 3, True)
  507. pointyShapeVolume(2, 4, False)
  508.  
  509.  
  510. # --------------------------------------------------------------------------------------------------------------------------------------
  511.  
  512.  
  513. # Practical 8B
  514. # Open a new file in IDLE (“New Window” in the “File” menu) and save it as geometry.py in the
  515. # dictionary where you keep the files you create for this course. Then copy the functions you wrote for
  516. # calculating volumes and areas in the “Conrol Flow and Functions” exercise into this file and save it.
  517. # Now open a new file and save it in the same directory. You should now be able to import geometry
  518. # Try and add priny dir(geometry) to the file and run it.
  519. # Now write a function pointyShapeVolume(x,y,squareBase) that calculates the volume of a square pyramid if
  520. # squareBase is True and of a right circularcone if squareBase is False. X is the length of an edge on a square
  521. # if squareBase is True and the radius of a circle when squareBase is False.y is the height of the object.First
  522. # use squareBase to distinguish the cases. Use the cicleArea and squareArea from the geometry module to
  523. # calculate the base areas.
  524.  
  525.  
  526. try:
  527.     number = int(input("Enter a number between 1-10:"))
  528.     r = 100/number
  529. except (ValueError):
  530.     print("Please enter number only")
  531. except (ZeroDivisionError):
  532.     print("Please enter number between 1-10")
  533. else:
  534.     print("Result:", r)
  535. finally:
  536.     print("you are in finally block")
  537.  
  538.  
  539. # --------------------------------------------------------------------------------------------------------------------------------------
  540.  
  541.  
  542. # Practical 9A
  543. # Try to configure the widget with various options like: bg=”red”, family=”times”, size=18
  544.  
  545.  
  546. m = t.Tk()
  547.  
  548.  
  549. def display1():
  550.     l = t.Label(m, text="Good Morning", bg='red', font=("Times 50"))
  551.     l.pack()
  552.  
  553.  
  554. def display():
  555.     l1 = t.Label(m, text="Good Morning", bg='blue', font=("Times 50"))
  556.     l1.pack()
  557.  
  558.  
  559. B = t.Button(m, text='ViewEffect blue', command=display, relief=SUNKEN)
  560. B.pack()
  561. B = t.Button(m, text='ViewEffect red', command=display1, relief=SUNKEN)
  562. B.pack()
  563. m.mainloop()
  564.  
  565.  
  566. # --------------------------------------------------------------------------------------------------------------------------------------
  567.  
  568.  
  569. # Practical 9B
  570. #: Try to change the widget type and configuration options to experiment with other widget types like
  571. # Message, Button, Entry, Checkbutton, Radiobutton, Scale etc.
  572.  
  573.  
  574. m = t.Tk()
  575. m.title("Fill your Details")
  576.  
  577.  
  578. def button():
  579.     selectionE = "Your Name:", str(va.get())
  580.     selectionCB = "\n Hobbies:", "Dance", str(
  581.         cvar1.get()), "Music", str(cvar2.get())
  582.     selectionRB = "\n Gender:", str(rvar1.get())
  583.     selectionS = "\n Marks:", str(varS.get())
  584.     selection = selectionE+selectionCB+selectionRB+selectionS
  585.     ls = t.Label(m, text=selection).grid()
  586.  
  587.  
  588. m1 = t.Message(m, text="Fill your Details").grid(row=1, column=0)
  589. l = t.Label(m, text="Enter your name:", relief="ridge").grid(row=2, column=0)
  590. va = StringVar()
  591. el = t.Entry(m, textvariable=va, width=30,
  592.              relief="raised").grid(row=2, column=1)
  593. l1 = t.Label(m, text="Select Your Hobbies:",
  594.              relief="raised").grid(row=3, column=0)
  595. cvar1 = IntVar()
  596. cvar2 = IntVar()
  597. c1 = Checkbutton(m, text="Dance", variable=cvar1,
  598.                  relief="raised").grid(row=3, column=1)
  599. c2 = Checkbutton(m, text="Music", variable=cvar2,
  600.                  relief="raised").grid(row=4, column=1)
  601. l2 = t.Label(m, text="Select your Gender:",
  602.              relief="ridge").grid(row=5, column=0)
  603. rvar1 = IntVar()
  604. r1 = t.Radiobutton(m, text="Male", variable=rvar1, value=1,
  605.                    relief="raised").grid(row=5, column=1)
  606. r2 = t.Radiobutton(m, text="Female", variable=rvar1, value=2,
  607.                    relief="raised").grid(row=6, column=1)
  608. l3 = t.Label(m, text="Enter your marks:", relief="ridge").grid(row=7, column=0)
  609. varS = DoubleVar()
  610. sc = t.Scale(m, from_=0, to=150, orient="horizontal", variable=varS, relief="raised").grid(row=7, column=1
  611.                                                                                            )
  612. b1 = t.Button(m, text="Submit", command=button).grid(row=8, column=0)
  613. m.mainloop()
  614.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement