Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 1A
- # Create a program that ask the user to enter their name and their age. Print out a message addressed to
- # them that tells them the year that they will turn 100 year old.
- import operator
- name = input("Whats your name::")
- age = int(input("how old you are::"))
- year = str((2017-age)+100)
- print(name+" you will be 100 year old in the year::"+year)
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 1B
- # Enter the number from user and depending on whether the number is even or odd, print out an
- # approrpriate message to the user.
- a = int(input("Enter any number::"))
- if a % 2 == 0:
- print("It's even number")
- else:
- print("It's odd number")
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 1C
- # Write a program to generate the fibonacci series.
- v = int(input("\n Please enter the range number: "))
- a = 0
- b = 1
- for n in range(0, v):
- if (n <= 1):
- c = n
- else:
- c = a+b
- a = b
- b = c
- print(c)
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 1D
- # Write a function that reverses the user defined value.
- def rev(num):
- a = 0
- while (num > 0):
- b = num % 10
- a = (a*10)+b
- num = num//10
- print("reverse number is::", a)
- a = int(input("Enter any number::"))
- rev(a)
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 1E
- #: Write a function to check the input value is Armstrong and also write the function for Palindrome
- def armstrong(num):
- sum = 0
- temp = num
- while temp > 0:
- digit = temp % 10
- sum += digit**3
- temp //= 10
- if num == sum:
- print(num, "is an armstrong number")
- else:
- print(num, "is not an armstrong number")
- def palindrome(num):
- n = num
- rev = 0
- while num != 0:
- rev = rev*10
- rev = rev+int(num % 10)
- num = int(num/10)
- if n == rev:
- print(n, "is palindrome number")
- else:
- print(n, "is not a palindrome number")
- num = int(input("Enter a number to check it is armstrong or not: "))
- armstrong(num)
- num = int(input("Enter a number to check it is palindrome or not: "))
- palindrome(num)
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 1F
- # Write a recursive function to print the factorial for a given number.
- def factorial(n):
- if n == 1:
- return 1
- else:
- return n*factorial(n-1)
- n = int(input('Enter a number::'))
- fact = factorial(n)
- print('factorial of', n, 'is', fact)
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 2A
- # :Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False
- # otherwise.
- def find_vowel(s):
- l=['a','e','i','o','u','A','E','I','O','U']
- for i in s:
- if i in l:
- print("True")
- else:
- print("False")
- s=input("Enter any word to check it vowel or not::")
- find_vowel(s)
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 2B
- # Define a function that computes the length of a given list or string
- def len_s(s):
- count = 0
- for i in s:
- if i != '':
- count += 1
- print('The total length of string:', count)
- s = input("Enter a string to check the length of it::")
- len_s(s)
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 2C
- # Define a procedure histogram() that takes a list of integers and prints a histogram to the screen. For
- # example, histogram([4, 9, 7]) should print the following
- def histogram(items):
- for n in items:
- output = ' '
- times = n
- while (times > 0):
- output += '*'
- times = times-1
- print(output)
- histogram([4, 9, 7])
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 3A
- # A pangram is a sentence that contains all the letters of the English alphabet at least once, for example:
- # The quick brown fox jumps over the lazy dog. Your task here is to write a function to check a sentence to
- # see if it is a pangram or not.
- import string
- def ispangram(sentence,alphabet=string.ascii_lowercase):
- aset=set(alphabet)
- return aset<=set(sentence.lower())
- print(ispangram(input("Enter the sentence:")))
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 3B
- # Take a list, say for example this one.
- a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- for i in a:
- if i < 5:
- print(i)
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 4A
- # Write a program that takes two lists and returns True if they have at least one common member
- list1 = [1, 2, 3, 4, 5, 6]
- list2 = [11, 12, 13, 14, 15, 6]
- for i in list1:
- for j in list2:
- if i == j:
- print('TRUE...The two list have at least one common element')
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 4B
- # Write a Python program to print a specified list after removing the 0th, 2nd, 4th and 5th elements.
- list = [1, 2, 3, 4, 5, 6, 7, 8]
- list = [x for (i, x) in enumerate(list) if i not in (0, 2, 4, 5)]
- print(list)
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 4C
- # Write a Python program to clone or copy a list
- list1 = [1, 2, 3, 4, 5]
- n = list(list1)
- print("list2=", n)
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 5A
- # Write a Python script to sort (ascending and descending) a dictionary by value
- dic = {'a1': 12, 'a3': 14, 'a4': 13, 'a2': 11, 'a0': 10}
- print('Original dictionary:', dic)
- ascending = sorted(dic.items(), key=operator.itemgetter(0))
- descending = sorted(dic.items(), key=operator.itemgetter(0), reverse=True)
- print('Ascending order:', ascending)
- print('Descending order:', descending)
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 5B
- # Write a Python script to concatenate following dictionaries to create a new one. Sample Dictionary
- dic1 = {1: 10, 2: 20}
- dic2 = {3: 30, 4: 40}
- dic3 = {5: 50, 6: 60}
- dic4 = {}
- for d in (dic1, dic2, dic3):
- dic4.update(d)
- print(dic4)
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 5C
- # Write a Python program to sum all the items in a dictionary.
- dict = {"key1": 5, "key2": 3, "key3": 7}
- print("Dictionary items")
- print(dict.values())
- print("Sum of dictionary values:", sum(dict.values()))
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 6A
- # Write a python program to read an entire text file #Contents of TextRead.txt File This is a text file
- # which will be read by this program and will display on screen
- # make dummy.txt and paste Hello Everyone and then save
- # code:
- f = open('dummy.txt', 'w+')
- f.write("Hello Everyone")
- f.seek(0)
- t = f.read()
- print(t)
- f.close()
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 6B
- # Write a Python program to append text to a file and display the text
- # TextRead.txt:
- '''
- First Line added to the file
- Second Line added to the file
- Third Line added to the file
- '''
- # code:
- with open("TextRead.txt", "a+")as file:
- file.write("\n Second Line added to the file")
- file.write("\n Third Line added to the file")
- text = open("TextRead.txt")
- print(text.read())
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 6C
- # Write a Python program to read last n lines of a file.
- f = open('TextRead.txt', 'r')
- s = f.readlines()
- print(s[1])
- f.close()
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 7A
- # Design a class that store the information of student and display the same.
- class student:
- def __init__(self, name, address, mobile, email):
- self.name = name
- self.address = address
- self.mobile = mobile
- self.email = email
- def display(self):
- print("Name:", name)
- print("Address:", address)
- print("Mobile:", mobile)
- print("Email:", email)
- print("Enter your details:")
- name = input("Enter your name:")
- address = input("Enter your address:")
- mobile = input("Enter your mobile:")
- email = input("Enter your Email:")
- s = student(name, address, mobile, email)
- s.display()
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 7B
- # Implement the concept of inheritance using python.
- class st:
- def s1(self):
- print("base class")
- class st1(st):
- def s2(self):
- print("derived class")
- t = st1()
- t.s1()
- t.s2()
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 7C
- # Create a class called Numbers, which has a single class attribute called MULTIPLIER, and a constructor
- # which takes the parameters x and y (these should all be numbers).
- # i. Write a method called add which returns the sum of the attributes x and y.
- # ii. Write a class method called multiply, which takes a single number parameter a and returns the product of
- # a and MULTIPLIER.
- # iii. Write a static method called subtract, which takes two number parameters, b and c, and returns b-c.
- # iv. Write a method called value which returns a tuple containing the values of x and y. Make this method
- # into a property, and write a setter and a deleter for manipulating the values of x and y
- class Number:
- Multiplier = 10
- def __init__(self, x, y):
- self.x = x
- self.y = y
- def add(self):
- return (self.x+self.y)
- @classmethod
- def multiply(cls, a):
- return (cls.Multiplier*a)
- @staticmethod
- def sub(b, c):
- return (b-c)
- @property
- def value(self):
- return (self.x, self.y)
- def s_value(self, x, y):
- self.x = x
- self.y = y
- def d_value(self):
- del self.x
- del self.y
- N = Number(20, 30)
- N = Number(20, 30)
- 24
- print("Addition=", N.add())
- print("Multiplication=", N.multiply(5))
- print("Subtraction=", Number.sub(9, 6))
- print("Property value=", N.value)
- print("Set value=", N.s_value(4, 3))
- print("Property value=", N.value)
- print("Deleted value=", N.d_value())
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 8A
- # Open a new file in IDLE (“New Window” in the “File” menu) and save it as geometry.py in the
- # dictionary where you keep the files you create for this course. Then copy the functions you wrote for
- # calculating volumes and areas in the “Conrol Flow and Functions” exercise into this file and save it.
- # Now open a new file and save it in the same directory. You should now be able to import geometry
- # Try and add priny dir(geometry) to the file and run it.
- # Now write a function pointyShapeVolume(x,y,squareBase) that calculates the volume of a square pyramid if
- # squareBase is True and of a right circularcone if squareBase is False. X is the length of an edge on a square
- # if squareBase is True and the radius of a circle when squareBase is False.y is the height of the object.First
- # use squareBase to distinguish the cases. Use the cicleArea and squareArea from the geometry module to
- # calculate the base areas.
- # make 2 files
- # 1. geometry.py:
- def sphereArea(r):
- return 4*math.pi*r**2
- def sphereVolume(r):
- return 4*math.pi*r**3/3
- def spherematrices(r):
- return sphereArea(r), sphereVolume(r)
- def circleArea(r):
- return math.pi*r**2
- def squareArea(x):
- return x**2
- # 2. demo.py (run this file only)
- def pointyShapeVolume(x, y, squareBase):
- if squareBase == True:
- print("Square area:", geometry.squareArea(x))
- else:
- print("Circle area:", geometry.circleArea(x))
- print(dir(geometry))
- pointyShapeVolume(2, 3, True)
- pointyShapeVolume(2, 4, False)
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 8B
- # Open a new file in IDLE (“New Window” in the “File” menu) and save it as geometry.py in the
- # dictionary where you keep the files you create for this course. Then copy the functions you wrote for
- # calculating volumes and areas in the “Conrol Flow and Functions” exercise into this file and save it.
- # Now open a new file and save it in the same directory. You should now be able to import geometry
- # Try and add priny dir(geometry) to the file and run it.
- # Now write a function pointyShapeVolume(x,y,squareBase) that calculates the volume of a square pyramid if
- # squareBase is True and of a right circularcone if squareBase is False. X is the length of an edge on a square
- # if squareBase is True and the radius of a circle when squareBase is False.y is the height of the object.First
- # use squareBase to distinguish the cases. Use the cicleArea and squareArea from the geometry module to
- # calculate the base areas.
- try:
- number = int(input("Enter a number between 1-10:"))
- r = 100/number
- except (ValueError):
- print("Please enter number only")
- except (ZeroDivisionError):
- print("Please enter number between 1-10")
- else:
- print("Result:", r)
- finally:
- print("you are in finally block")
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 9A
- # Try to configure the widget with various options like: bg=”red”, family=”times”, size=18
- m = t.Tk()
- def display1():
- l = t.Label(m, text="Good Morning", bg='red', font=("Times 50"))
- l.pack()
- def display():
- l1 = t.Label(m, text="Good Morning", bg='blue', font=("Times 50"))
- l1.pack()
- B = t.Button(m, text='ViewEffect blue', command=display, relief=SUNKEN)
- B.pack()
- B = t.Button(m, text='ViewEffect red', command=display1, relief=SUNKEN)
- B.pack()
- m.mainloop()
- # --------------------------------------------------------------------------------------------------------------------------------------
- # Practical 9B
- #: Try to change the widget type and configuration options to experiment with other widget types like
- # Message, Button, Entry, Checkbutton, Radiobutton, Scale etc.
- m = t.Tk()
- m.title("Fill your Details")
- def button():
- selectionE = "Your Name:", str(va.get())
- selectionCB = "\n Hobbies:", "Dance", str(
- cvar1.get()), "Music", str(cvar2.get())
- selectionRB = "\n Gender:", str(rvar1.get())
- selectionS = "\n Marks:", str(varS.get())
- selection = selectionE+selectionCB+selectionRB+selectionS
- ls = t.Label(m, text=selection).grid()
- m1 = t.Message(m, text="Fill your Details").grid(row=1, column=0)
- l = t.Label(m, text="Enter your name:", relief="ridge").grid(row=2, column=0)
- va = StringVar()
- el = t.Entry(m, textvariable=va, width=30,
- relief="raised").grid(row=2, column=1)
- l1 = t.Label(m, text="Select Your Hobbies:",
- relief="raised").grid(row=3, column=0)
- cvar1 = IntVar()
- cvar2 = IntVar()
- c1 = Checkbutton(m, text="Dance", variable=cvar1,
- relief="raised").grid(row=3, column=1)
- c2 = Checkbutton(m, text="Music", variable=cvar2,
- relief="raised").grid(row=4, column=1)
- l2 = t.Label(m, text="Select your Gender:",
- relief="ridge").grid(row=5, column=0)
- rvar1 = IntVar()
- r1 = t.Radiobutton(m, text="Male", variable=rvar1, value=1,
- relief="raised").grid(row=5, column=1)
- r2 = t.Radiobutton(m, text="Female", variable=rvar1, value=2,
- relief="raised").grid(row=6, column=1)
- l3 = t.Label(m, text="Enter your marks:", relief="ridge").grid(row=7, column=0)
- varS = DoubleVar()
- sc = t.Scale(m, from_=0, to=150, orient="horizontal", variable=varS, relief="raised").grid(row=7, column=1
- )
- b1 = t.Button(m, text="Submit", command=button).grid(row=8, column=0)
- m.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement