Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #1. Python program to evaluate Values, expressions, and statements, Conditional execution, and Functions Iterations
- #a. prompt the user to enter an integer and reverse it. And print the sum of the reversed integer.
- num=int(input("enter a number containing more than 1 integer "))
- revnum = 0
- while num!=0:
- digit = num % 10
- revnum = revnum * 10 + digit
- num //= 10
- print("the reversed of given number is ",revnum)
- sum = 0
- for i in str(revnum):
- sum = sum + int(i)
- print("the sum of the reversed numbers is ",sum)
- #b. Write a python program to find whether a number (num1) is a factor of 255.
- num1=int(input("enter a number "))
- if 255%num1==0:
- print("the given number is a factor of 255")
- else:
- print("the given number is not a factor of 255")
- #d. Write a program to find the sum of the following series:
- #i. 1 + 1/3 + 1/5 + 1/7 + .... up to ‘N’ terms.
- sum = 0
- numofterms=int(input("enter number of elements "))
- for i in range(1, numofterms + 1):
- sum = sum + 1.0 / (2 * i - 1)
- print(sum)
- #ii. 1 + x/1! + x3/2! + x5/3! + x7/4 + .... x2n-1/n!
- def factorial(num):
- fact=1
- for i in range(1,num+1):
- if num==1:
- return fact
- else:
- fact=fact*i
- return fact
- x=int(input("enter the value of x\n"))
- n=int(input("enter the value of n\n"))
- final_result=1
- for i in range(1,n+1):
- g=factorial(i)
- final_result=final_result+((x**((2*n)-1))/g)
- print("the sum is=",final_result)
- """- [ ] 2. Python program to evaluate Python Collections
- a. Write a Python Program to demonstrate the inbuilt functions of Strings, List,and sets.
- """
- # string reversal
- a=input("Enter the word to be reversed:")
- print(a[::-1])
- a=input("Enter the word to reverse:")
- b=len(a)
- for i in range(-1,-b-1,-1):
- print(a[i],end="")
- a=input("Enter the word to reverse:")
- b=len(a)
- i=-1
- while(i!=-b-1):
- print(a[i],end="")
- i=i-1
- # abrreviation
- a=input("Enter the word:")
- l=a.split()
- n=[]
- for i in range(0,len(l)):
- print(l[i][0].upper(),end="")
- # accept nos till done and sum and avr
- l=[]
- while 1:
- a=input("Enter the number:")
- if(a.lower()=='done'):
- break
- else:
- l.append(int(a))
- c=sum(l)
- f=len(l)
- average=c/f
- print("Average:",average)
- #
- b. Write a Python program for counting a specific letter 'o' in a given string; the
- number of times vowel ‘o’ appears.
- str1= "Hello World,"
- """d. Store the following for ‘n’ countries, using a dictionary:
- i. Name of a country, country’s capital, per capita income of the
- Write a Python Program to find the frequency of each word in given
- strings/strings
- country.
- ii. Write a program to display details of the country with the highest and second lowest per capita income."""
- countries_dictn=dict()
- countries_dictn
- n=int(input("Enter the number of entries"))
- i=1
- while(i<=n):
- country=input("Enter Country")
- cap=input("Enter Capital")
- capInc=input("Enter per capita income")
- countries_dictn[country]=(cap,capInc)
- i=i+1
- dict_keys=list(countries_dictn.keys())
- print("\nCountry\t\tCapital\t\tPer Capita Income")
- for ckey in dict_keys:
- details=countries_dictn[ckey]
- print("\n",ckey,'\t\t',end='')
- for val in details:
- print(val, end='\t\t')
- perCaptaInc=[]
- for ckey in dict_keys:
- details=countries_dictn[ckey]
- print(details[1])
- perCaptaInc.append(details[1])
- indmin=perCaptaInc.index(min(perCaptaInc))
- print("The country with Minimum per capita income is:",dict_keys[indmin])
- indmax=perCaptaInc.index(max(perCaptaInc))
- print("The country with Maximum per capita income is:",dict_keys[indmax])
- """
- #-[ ] 3. Write a python program to create two classes “Python” and “Java” having data members “Version” and “name” and a member function “display()”. With the help of the object, print the appropriate messages.
- #Prog 3
- class Python:
- version = 3.3
- name = "Python"
- def display(self):
- print("Python name and version is",self.name,self.version)
- class Java:
- version = 1.8
- name = "JDK"
- def display(self):
- print("Java name and version is",self.name,self.version)
- a=Python()
- b=Java()
- a.display()
- print("-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-")
- b.display()
- #- [ ] 4. Create a class “Employee” with _init_ method to initialize data members: Name, Designation, Ph. No., and a member function display(). Create an instance for the class and display the details of the employee
- #Prog 4
- class Employee:
- def __init__(self,name='',designation='',phone=0):
- self.name=name
- self.designation=designation
- self.phone=phone
- def display(self):
- print("Name:",self.name ,"\n")
- print("Designation:",self.designation, "\n")
- print("Phone No:",self.phone ,"\n")
- emp1=Employee("Raj","Technical Advisor",8325772891)
- emp2=Employee("Sanju","Financial Advisor",6983762781)
- emp3=Employee("Rachit","Customer Support Advisor",8746587362)
- emp1.display()
- print("---------------------")
- emp2.display()
- print("---------------------")
- emp3.display()
- """
- - [ ] 5. Write an interactive calculator! User input is assumed to be a formula that consist of a number, an operator (at least + and -), and another number, separated by white space (e.g. 1 + 1). Split user input using str.split(), and check whether the resulting list is valid:
- a. If the input does not consist of 3 elements, raise a FormulaError, which is a custom Exception.
- b. Try to convert the first and third input to a float (like so: float_value = float(str_value)). Catch any ValueError that occurs, and instead raise a FormulaError
- c. If the second input is not '+' or '-', again raise a FormulaError
- d. If the input is valid, perform the calculation and print out the result. The user
- is then prompted to provide new input, and so on, until the user enters quit.#/
- """
- class FormulaError(Exception):
- pass
- while True:
- try:
- formula = input("Enter a formula (e.g. 1 + 1): ")
- if formula.lower() == "quit":
- break
- elements = formula.split()
- if len(elements) != 3:
- raise FormulaError("Formula must consist of three elements: number, operator, number")
- try:
- x = float(elements[0])
- y = float(elements[2])
- except ValueError:
- raise FormulaError("Number must be a valid float")
- if elements[1] == "+":
- result = x + y
- elif elements[1] == "-":
- result = x - y
- elif elements[1] == "*":
- result = x * y
- elif elements[1] == "/":
- result = x / y
- elif elements[1] == "%":
- result = x % y
- else:
- raise FormulaError("Operator must be '+' or '-' or '*' or '/' or '%'")
- print(f"Result: {result}")
- except FormulaError as e:
- print(e)
- """
- class FormulaError(Exception):
- pass
- def parse_input(user_input):
- input_list = user_input.split()
- if len(input_list)!=3:
- raise FormulaError("input doesn't consist of three elements")
- n1,op,n2=input_list
- try:
- n1=float(n1)
- n2=float(n2)
- except ValueError:
- raise FormulaError("the first and third input value must be numbers")
- return n1,op,n2
- def calculate(n1,op,n2):
- if op=='+':
- return n1+n2
- if op=='-':
- return n1-n2
- if op=='*':
- return n1*n2
- if op=='/':
- return n1/n2
- raise FormulaError('(0) is not a valid operator'.format(op))
- while True:
- user_input=input('>>>>')
- if user_input=='quit':
- break
- n1,op,n2=parse_input(user_input)
- result=calculate(n1,op,n2)
- print(result)
- """
- """
- 6. Write a Python program to count the number of lines in a text file and read the file line by line and store it into a list as well as find the longest word in the file.
- """
- # Write a Python program to count the number of lines in a text file
- f=open("test.txt","w")
- f.write("hello world123\n")
- f.write("hello world456\n")
- f.write("hello world789\n")
- f.write("hello world101010110\n")
- f.close()
- f=open("test.txt","r")
- def count_lines(f):
- count=0
- for i in f:
- count+=1
- return count
- print("the number of lines is ",count_lines(f))
- f=open("test.txt","r")
- for i in f:
- print(i)
- f.close()
- f=open("test.txt","r")
- a=[]
- print("the list elemens are:")
- for i in f:
- a.append(i)
- print(a)
- f.close()
- # find the longest word in the file and print it
- def longest_word():
- with open('test.txt') as f:
- words = f.read().split()
- print("the longest word is",max(words, key=len))
- longest_word()
- """
- - [ ] 7. Write a Python program to create a list of student details: usn, name dob and email {using dictionary} and write a list to a file.
- """
- dict={}
- while True:
- roll = input("Enter the roll no. of the student(enter Q to quit)=")
- if roll=='Q' or roll=='q':
- break
- else:
- usn=input('Enter the USN of the Student:')
- name=input('Enter the Name of the Student:')
- dob=input('Enter the DOB of the Student:')
- email=input('Enter the Email of the Student:')
- dict[roll]={usn,name,dob,email}
- print(dict)
- filename="samplefile.txt"
- with open(filename,'w') as givenfilecontent:
- for key,value in dict.items():
- givenfilecontent.write('%s:%s\n'%(key,value))
- """
- - [ ] 8. Generate one-hot encodings for an array in numpy.
- """
- import numpy as np
- def OHE(array):
- n = np.max(array) + 1
- return np.eye(n)[array]
- array = np.array([1,4,5,6,7])
- print(OHE(array))
- """
- - [ ] 9. Write a Pandas program to import excel data into a Pandas dataframe and find a list of
- employees where hire_date is between two specific month and year.
- """
- import pandas as pd
- df = pd.read_excel('empl.xlsx')
- df.set_index('emp_id', inplace=True)
- df['hire_date'] = pd.to_datetime(df['hire_date'])
- req = df[(df['hire_date'].dt.month >= 1) & (df['hire_date'].dt.month <= 3) & (df['hire_date'].dt.year == 2022)]
- print(req)
- """1. Write a python program to create two classes “Python” and “Java” having data members “Version” and “name” and a member function “display()”. With the help of the object, print the appropriate messages."""
- class Python:
- '''This is a class explaining about python'''
- Version = "3.9"
- Name = "Python" #data members
- def display_Python(self):
- print("Hello Python")
- class Java(Python):
- '''This is a class explaining about Java'''
- Version = "15.1"
- Name = "Java"
- def display_Java(self):
- print("Hello Java")
- Obj_1 = Python()
- Obj_2 = Java()
- Obj_2.display_Python()
- "2. Write a python program to demonstrate the usage of the __init__ method and self parameter"
- class Python:
- """This is the class about
- Python Programming Lanugage"""
- def __init__(self,Version,Name):
- self.Version = Version
- self.Name = Name
- def display(self):
- print("This is display Fun", self.Name)
- P1 = Python(3.9,"Python")
- print(P1.Version)
- del P1.Version
- print(P1.Version)
- P1.display()
- "3. Create a class “Employee” with data members Name, Designation, Ph.No, and member function display(). Create an instance for the class and display the details of the employee"
- class Employee:
- "Employee class containing the details"
- def __init__(self, Name, Designation, PhNo):
- self.Name = Name
- self.Designation = Designation
- self.PhNo = PhNo
- def display(self):
- print("The Name of employee is", self.Name)
- print("The Designation of employee is", self.Designation)
- print("The Ph.No of employee is", self.PhNo)
- Emp1 = Employee("Joey","Manager",9999888888)
- Emp1.display()
- "4. Write a Python program to demonstrate single inheritance."
- class Person:
- def __init__(self, fname, lname):
- self.firstname = fname
- self.lastname = lname
- def printname(self):
- print(self.firstname, self.lastname)
- class Student(Person):
- def __init__(self, fname, lname, year):
- super().__init__(fname, lname)
- self.graduationyear = year
- y = Person("John","nike")
- x = Student("Mike", "Olsen", 2019)
- print(x.graduationyear)
- print("isinstance", isinstance(y,Student))
- print("Value is ",x = Person)
- "5. Write a Python Program to demonstrate the concept of Classes and Objects."
- def diffcar(self, name, make, model):
- self.name=name
- self.make=make
- self.model=model
- Car.car_count+=1
- car_a=Car()
- car_a.diffcar("Camry", "Toyota", 2021)
- print(car_a.car_count)
- car_b=Car()
- car_b.diffcar("Altima", "Nissan", 2020)
- print(car_a.car_count)
- "6. Write a Python Program to demonstrate Inheritance"
- class Person:
- def __init__(self, fname, lname):
- self.firstname = fname
- self.lastname = lname
- def printname(self):
- print(self.firstname, self.lastname)
- class Student(Person):
- def __init__(self, fname, lname, year):
- Person.__init__(self, fname, lname)
- self.year=year
- x = Student("Mike", "Olsen", 2021)
- x.printname()
- print(x.year)
- "7. Write Python Program to demonstrate Inheritance."
- class Calculation1:
- def Summation(self,a,b):
- return a+b;
- class Calculation2:
- def Multiplication(self,a,b):
- return a*b;
- class Calculation3(Calculation1,Calculation2):
- def Divide(self,a,b):
- return a/b;
- d =Calculation3()
- print(d.Summation(10,20))
- print(d.Multiplication(10,20))
- print(d.Divide(10,20))
- "8. Write a Python Program to demonstrate Single Inheritance "
- class Animal:
- def speak(self):
- print("Animal is speaking")
- class Dog(Animal):
- def bark(self):
- print("Dog is barking")
- xyz=Dog()
- xyz.bark()
- xyz.speak()
- "9. Write a Python Program to demonstrate Multilevel Inheritance"
- class Animal:
- def speak(self):
- print("Animal is speaking")
- class Dog(Animal):
- def bark(self):
- print("Dog is barking")
- class Dogchild(Dog):
- def drink(self):
- print("Dog is drinking")
- xyz=Dogchild()
- xyz.drink()
- xyz.bark()
- xyz.speak()
- "10. Write a Python Program to demonstrate Multiple Inheritance"
- class Calculator1:
- def sum(self, a, b):
- return a+b
- class Calculator2:
- def mul(self, a, b):
- return a*b
- class Derived(Calculator1, Calculator2):
- def div(self, a, b):
- return a/b
- a=Derived()
- a.sum(4,2)
- a.mul(4,2)
- a.div(4,2)
- "11. Write a Python Program to demonstrate accessing attributes of class"
- class emp:
- name = 'sumukh'
- salary = '25000'
- def show(self):
- print(self.name)
- print(self.salary)
- e1 = emp()
- # Use getattr instead of e1.name
- print(getattr(e1, 'name'))
- # returns true if object has attribute
- # delete the attribute
- delattr(emp, 'salary')
- print(hasattr(e1, 'name'))
- # sets an attribute
- setattr(e1, 'height', 152)
- # returns the value of attribute name height
- print(getattr(e1, 'height'))
- "12. Write a Python Program to demonstrate Single Inheritance"
- class A:
- def feature1(self):
- print("feature 1 is working")
- def feature2(self):
- print("feature 2 is working")
- a1 = A()
- a1.feature1()
- a1.feature2()
- class B(A):
- def feature3(self):
- print("feature 3 is working")
- b1 = B()
- b1.feature3()
- "13. Create a Bus class that inherits from the Vehicle class. Give the capacity argument of Bus.seating_capacity() a default value of 50."
- class Vehicle:
- def __init__(self, name, max_speed, mileage):
- self.name = name
- self.max_speed = max_speed
- self.mileage = mileage
- def seating_capacity(self, capacity):
- return f"The seating capacity of a {self.name} is {capacity} passengers"
- class Bus(Vehicle):
- # assign default value to capacity
- def seating_capacity(self, capacity=50):
- return super().seating_capacity(capacity=50)
- School_bus = Bus("School Volvo", 180, 12)
- print(School_bus.seating_capacity())
Advertisement
Add Comment
Please, Sign In to add comment