JNTUK R20 PYTHON PROGRAMMING LAB

R20 PYTHON PROGRAMMING LAB
  1. 1. Write a program that asks the user for a weight in kilograms and converts it to pounds. There are 2.2 pounds in a kilogram.
  2. weight = float(input("enter ur weight: "))
    
    pound = (2.2 * weight)
    
    print("After coverting Kgs into pounds is %0.2f" %pound)
    


  3. 2. Write a program that asks the user to enter three numbers (use three separate input statements). Create variables called total and average that hold the sum and average of the three numbers and print out the values of total and average.
  4.  
    a=int(input("enter value of a: "))
    b=int(input("enter value of b: "))
    c=int(input("enter value of c: "))
    Total = (a+b+c) 
    Average = Total/3 
    print("sum of three numbers is ", Total)
    print("Avg of three numbers is ", Average)
    print("sum of three numbers is %d and Avg of three numbers is %0.2f " %(Total,Average))
    


  5. 3. Write a program that uses a for loop to print the numbers 8, 11, 14, 17, 20, . . . , 83, 86, 89.
  6.  
    for i in range(8,90,3):
        print(i,end=' ')
    


  7. 4. Write a program that asks the user for their name and how many times to print it. The program should print out the user's name the specified no of times
  8. username=input("enter ur name")
    n=int(input("how many no of times to print"))
    c=1
    while c<=n:
        print("u r name is ",username)
        c=c+1
    


  9. 5. Use a for loop to print a triangle like the one below. Allow the user to specify how high the triangle should be.
  10. n=15
    for i in range(0,n):
        for j in range(0,i+1):
            print("*",end='')
        print()
    

    or

    for i in range(1,15):
        print(i*"*")
    


  11. 6. Generate a random number between 1 and 10. Ask the user to guess the number and print a message based on whether they get it right or not.
  12. import random as ra 
    random_num = ra.randint(1, 10) 
    guess=int(input('Guess a number between 1 and 10 until you get it right :'))
    while random_num != guess:
              print("try again ")
              guess = int(input('Guess a number between 1 and 10 until you get it right : ')) 
    print('Well guessed!')
    
    


  13. 7. Write a program that asks the user for two numbers and prints Close if the numbers are within .001 of each other and Not close otherwise.
  14. num1 = float(input("Enter the first number: "))
    num2 = float(input("Enter the second number: "))
    
    if abs(num1 - num2) <= 0.001:
        print("Close")
    else:
        print("not close")
     


  15. 8. Write a program that asks the user to enter a word and prints out whether that word contains any vowels.
  16. vowels = ['A', 'E', 'I', 'o', 'U', 'a', 'e', 'i', 'o', 'u']
    a=input("enter word") 
    c=0 
    for i in a: 
        if(i in vowels):
            c=c+1 
    if(c!=0):
        print("string contains vowels")
    


  17. 9. Write a program that asks the user to enter two strings of the same length. The program should then check to see if the strings are of the same length. If they are not, the program should print an appropriate message and exit. If they are of the same length, the program should alternate the characters of the two strings. For example, if the user enters abcde and ABCDE the program should print out AaBbCcDdEe.
  18. a=input("enter string 1: ")
    b=input("enter string 2: ")
    #result=''
    if(len(a)==len(b)):
        for i in range(len(a)):
            result=a[i]+b[i]
            print(result,end='')
    else:
        print("please enter equal length strings") 
    


  19. 10. Write a program that asks the user for a large integer and inserts commas into it according to the standard American convention for commas in large numbers. For instance, if the user enters 1000000, the output should be 1,000,000.
  20. n=int(input()) 
    print("{:,}".format(n))
    
  21. 11. In algebraic expressions, the symbol for multiplication is often left out, as in 3x+4y or 3(x+5). Computers prefer those expressions to include the multiplication symbol, like 3*x+4*y or 3*(x+5). Write a program that asks the user for an algebraic expression and then inserts multiplication symbols where appropriate.
  22. n=input()
    l=list(n)
    print("list is",l)
    res=''
    i=0
    while(i<len(l)):
        if l[i]=='(':
            ind=l.index(')')
            str=''.join(l[i:ind+1])
            res=res+'*'+str
            i=i+len(str)
        elif l[i].isalpha():
            res=res+'*'+l[i]
            i=i+1
        else:
            res=res+l[i]
            i=i+1
    print(res)
     


  23. 12. Write a program that generates a list of 20 random numbers between 1 and 100. (a) Print the list. (b) Print the average of the elements in the list. (c) Print the largest and smallest values in the list. (d) Print the second largest and second smallest entries in the list (e) Print how many even numbers are in the list.
  24. import random as ra
    list=[]
    for i in range(20):
        list.append(ra.randint(1, 100))
    print(list)
    #print the average of the elements in the list
    sum=0
    for i in range(20):
        sum=sum+list[i]
    print("average of all the elements in the list is ", sum/len(list))
    #Print the second largest and second smallest entries in the list
    lar=lar2=small=small2=list[0]
    for i in list[1:]:
        if i > lar:
            lar2 = lar
            lar = i 
        elif lar2 < i: 
            lar2 = i 
        if i < small: 
            small2 = small
            small = i 
        elif small2 > i: 
            small2 = i 
    print("Largest element is : ", lar)
    print("Second Largest element is : ", lar2)
    print("Smallest element is : ", small)
    print("Second Smallest element is : ", small2)
    #Print the even numbers in the list
    for num in list:
        if num%2==0:
            print(num,end=' ')
    #list comprehension 
    even = [num for num in list if num % 2 != 0]
    print(even)
    


  25. 13. Write a program that asks the user for an integer and creates a list that consists of the factors of that integer.
  26. x=int(input("enter any number: "))
    list1=[]
    for i in range(1, x + 1):
        if x % i == 0:
            list1.append(i)
    print(list1)
    
    #list comprehension
    list=[i for i in range(1, x + 1) if x % i == 0]
    print(list)
    


  27. 14. Write a program that generates 100 random integers that are either 0 or 1. Then find the longest run of zeros, the largest number of zeros in a row. For instance, the longest run of zeros in [1,0,1,1,0,0,0,0,1,0,0] is 4.
  28. import random as ra
    list=[]
    for i in range(100):
        list.append(ra.randint(0, 1))
    print(list)
    c=0
    maxc=0
    for i in list:
        if i == 0:
            c += 1
        else:
            if c > maxc:
                maxc = c
            c = 0
    print("the longest run of zeros",maxc)
    


  29. 15. Write a program that removes any repeated items from a list so that each item appears at most once. For instance, the list [1,1,2,3,4,3,0,0] would become [1,2,3,4,0].
  30. list=[1,1,2,3,4,3,0,0]
    list1=[]
    for i in list:
        if i not in list1:
            list1.append(i)
    
    print(list1)
    


  31. 16. Write a program that asks the user to enter a length in feet. The program should then give the user the option to convert from feet into inches, yards, miles, millimeters, centimeters, meters, or kilometers. Say if the user enters a 1, then the program converts to inches, if they enter a 2, then the program converts to yards, etc. While this can be done with if statements,it is much shorter with lists and it is also easier to add new conversions if you use lists.
  32. n=float(input("Enter Feet"))
    list=[]
    list.append(n*12)
    list.append(n* 0.33333)
    list.append(n*0.00018939)
    list.append(n*304.8,2)
    list.append(n*30.48)
    list.append(n/ 3.2808)
    list.append(n/ 3280.8)
    print(list)
    print("0.Convert Feet to Inches")
    print("1.Convert Feet to Yards")
    print("2.Convert Feet to Miles")
    print("3.Convert Feet to millimeters")
    print("4.Convert Feet to centimeters")
    print("5.Convert Feet to meters")
    print("6.Convert Feet to kilometers")
    op=int(input("Choose Options from Above"))
    print(list[op])
    

    or

    n=float(input("Enter Feet"))
    
    print("1.Convert Feet to Inches")
    print("2.Convert Feet to Yards")
    print("3.Convert Feet to Miles")
    print("4.Convert Feet to millimeters")
    print("5.Convert Feet to centimeters")
    print("6.Convert Feet to meters")
    print("7.Convert Feet to kilometers")
    op=int(input("Choose Options from Above"))
    
    
    if(op==1):
        Inches=n*12
        print("Feet to Inches value is ", Inches)
    if(op==2):
        Yards= n * 0.33333
        print("Feet to Yards value is ", Yards)
    if(op==3):
        Miles= n * 0.00018939
        print("Feet to Miles value is ", Miles)
    if(op==4):
        MM= n * 304.8
        print("Feet to millimeters value is ", MM)
    if(op==5):
        CM= n * 30.48
        print("Feet to centimeters value is ", CM)
    if(op==6):
        meters= n / 3.2808
        print("Feet to meters value is ", round(meters,3))
    if(op==7):
        KM= n / 3280.8
        print("Feet to kilometers value is ", KM)
    


  33. 17. Write a function called sum_digits that is given an integer num and returns the sum of the digits of num.
  34.  def sum_digits(n):
        sum=0
        while n>0:
            m=n%10
            sum=sum+m
            n=n//10
        return sum
    
    n=int(input("enter value: "))
    print("sum of digits is: ", sum_digits(n))
    

    or

    def Sum(n): 
         
        sum = 0
        for i in n:  
          sum += int(i)       
        return sum
        
    n = input("enter value: ")
    print("sum of digist is: ",Sum(n))
    


  35. 18. Write a function called first_diff that is given two strings and returns the first location in which the strings differ. If the strings are identical, it should return -1.
  36. def first_diff(str1,str2):
        if str1 == str2:
            return -1 
        else:
            return str1.find(str2)
        
    str1=input("enter string 1: ")
    str2=input("enter string 2: ")
    
    print(first_diff(str1,str2))
    


  37. 19. Write a function called number_of_factors that takes an integer and returns how many factors the number has.
  38. def number_of_factors(n):
        list=[i for i in range(1, n + 1) if n % i == 0]
        return len(list)
        
    print("number has %d factors" %number_of_factors(20))
    


  39. 20. Write a function called is_sorted that is given a list and returns True if the list is sorted and False otherwise.
  40. def is_sorted1(list2):
        c = 0
        list1=list2[:]
        list1.sort()
        if(list2 != list1):
            c = 1
        if(not c):
            return True
        else:
            return False
            
    list2 = [121, 14, 15, 82, 100]    
    print(is_sorted1(list2))
    


  41. 21. Write a function called root that is given a number x and an integer n and returns x1/n. In the function definition, set the default value of n to 2.
  42. import math
    #Method 1
    def root(x,n):
        return pow(x,1/n)
    
    n=2
    x=int(input("enter value"))
    print("Method 1 using pow ", root(x,n), "
          Method 2, If n value is 2 only using sqrt function ",math.sqrt(x))
    


  43. 22. Write a function called primes that is given a number n and returns a list of the first n primes. Let the default value of n be 100.
  44. def primes(n):
        list=[]
        for num in range(n+1):
            if num > 1:
                for i in range(2, num):
                    if (num % i) == 0:
                        break
                else:
                    list.append(num)
        return list
    
    n=int(input("enter n value: "))
    print("list of n prime numbers are :", primes(n))
    


  45. 23. Write a function called merge that takes two already sorted lists of possibly different lengths, and merges them into a single sorted list. (a) Do this using the sort method. (b) Do this without using the sort method.
  46. #Without sort Method
    def merge(list1,list2):
        list3=list1+list2
        print(list3)
        for i in range (len(list3)):
            for j in range(i + 1, len(list3)):
                if(list3[i] > list3[j]):
                    temp = list3[i]
                    list3[i] = list3[j]
                    list3[j] = temp
        print(list3)
    
    list1=[1,2,3,5,6]
    list2=[3,5,9,10]
    merge(list1,list2)
    
    #sort Method
    def merge(list1,list2):
        list3=list1+list2
        list3.sort()
        print("After merging two list in sorted order",list3)
    
    list1=[1,2,3,5,6]
    list2=[3,5,9,10]
    merge(list1,list2)
    


  47. 24. Write a program that asks the user for a word and finds all the smaller words that can be made from the letters of that word. The number of occurrences of a letter in a smaller word can't exceed the number of occurances of the letter in the user's word.
  48. from itertools import permutations
    s=input('Enter a word:::')
    for i in range(2,len(s)):
        for p in permutations(s,i):
            print(''.join(p),end=' ')
    


  49. 25. Write a program that reads a file consisting of email addresses, each on its own line. Your program should print out a string consisting of those email addresses separated by semicolons
  50. import re
    
    fo = open("sample.txt", "r+")
    
    str = fo.read()
    print ("Read String is : ", str)
     
    lst = re.findall('\S+@\S+', str)     
    
    print(";"+lst[0]+";")
    fo.close()
    


  51. 26. Write a program that reads a list of temperatures from a file called temps.txt, converts those temperatures to Fahrenheit, and writes the results to a file called ftemps.txt.
  52. fo = open("temps.txt")
    f1= open("ftemps.txt","w+")
    for i in fo:
        c=float(i)
        F=(9*c + (32*5))/5
        f1.write(str(F)+"\n")
    f1.close()
    fo.close()
    


  53. 27. Write a class called Product. The class should have fields called name, amount, and price, holding the product's name, the number of items of that product in stock, and the regular price of the product. There should be a method get_price that receives the number of items to be bought and returns a the cost of buying that many items, where the regular price is charged for orders of less than 10 items, a 10% discount is applied for orders of between 10 and 99 items, and a 20% discount is applied for orders of 100 or more items. There should also be a method called make_purchase that receives the number of items to be bought and decreases amount by that much.
  54. class Product:
        def __init__(self,name,amount,price):
            self.name=name
            self.amount=amount
            self.price=price
            
        def get_price(self,number_items):
            if number_items<10:
                return self.price*number_items
            elif 10 <=number_items < 100:
                return 0.9*self.price*number_items
            else:return 0.8*self.price*number_items
        
        def make_purchase(self, quantity):
            self.amount -= quantity
    
    name, amount, price = 'shoes', 200, 1200
    
    shoes = Product(name, amount, price)
    
    q1 = 4
    print(f'cost for {q1} {shoes.name} = {shoes.get_price(q1)}')
    shoes.make_purchase(q1)
    print(f'remaining stock: {shoes.amount}\n')
    
    q2 = 12
    print(f'cost for {q2} {shoes.name} = {shoes.get_price(q2)}')
    shoes.make_purchase(q2)
    print(f'remaining stock: {shoes.amount}\n')
    
    q3 = 112
    print(f'cost for {q3} {shoes.name} = {shoes.get_price(q3)}')
    shoes.make_purchase(q3)
    print(f'remaining stock: {shoes.amount}\n')
    


  55. 28. Write a class called Time whose only field is a time in seconds. It should have a method called convert_to_minutes that returns a string of minutes and seconds formatted as in the following example: if seconds is 230, the method should return '5:50'. It should also have a method called convert_to_hours that returns a string of hours, minutes, and seconds formatted analogously to the previous method.
  56. class Time():
       # constructor
       def __init__(self, seconds):
           self.seconds = seconds
      
       # function to convert and return a string of minutes and seconds
       def convert_to_minutes(self):
           mins = self.seconds//60 # get the total minutes in the given seconds
           secs = self.seconds - (mins*60) # get the remaining seconds
           print("{}:{} minutes".format(self.seconds//60,self.seconds%60))
           # return the string of minutes:seconds
           return "%d:%d minutes" %(mins,secs)
      
       # function to convert and return string of hours, minutes, and seconds
       def convert_to_hours(self):
           secs = self.seconds
           hours = secs//3600 # get the total hours in the given seconds
           secs = secs - (hours*3600) # get the remaining seconds
           mins = secs//60 # get the total minutes in the remaining seconds
           secs = secs - (mins*60) # get the remaining seconds
           print("{:.2f} Hors".format(self.seconds/3600))
           # return the string of hours:minutes:seconds
           return "%d:%d:%d" %(hours,mins,secs)
          
    time = Time(365)
    print(time.convert_to_minutes())
    time = Time(4520)
    print(time.convert_to_hours())
    


  57. 29. Write a class called Converter. The user will pass a length and a unit when declaring an object from the class for example, c = Converter(9,'inches'). The possible units are inches, feet, yards, miles, kilometers, meters, centimeters, and millimeters. For each of these units there should be a method that returns the length converted into those units. For example, using the Converter object created above, the user could call c.feet() and should get 0.75 as the result.
  58.  class Converter:
        def __init__(self, n,name):
            self.value = n
            self.name=name
        
        def FeettoInches(self):
            Inches=self.value*12
            print("Feet to Inches value is ", Inches)
            
        def milestokm(self):
            km=self.value/0.62137
            print("miles to KM  is ", km)
                
        def FeettoYards(self):
            Yards= self.value * 0.3333
            print("Feet to Yards value is ", Yards)
        
        def FeettoMiles(self):
            Miles= self.value * 0.00018939
            print("Feet to Miles value is ", Miles)     
            
    n=float(input("enter feet/inches/cm/mm/km/miles: "))
    x=Converter(n,'inches')
    
    x.FeettoInches()
    x.milestokm()
    x.FeettoYards()
    x.FeettoMiles()
    


  59. 30. Write a Python class to implement pow(x, n).
  60. class power:
        
        def pow1(self, x, n):
            if x==0 or x==1 or n==1:
                return x 
    
            if x==-1:
                if n%2 ==0:
                    return 1
                else:
                    return -1
            if n==0:
                return 1
            if n<0:
                return 1/self.pow1(x,-n)
            val = self.pow1(x,n//2)
            if n%2 ==0:
                return val*val
            return val*val*x
    
    x=power()
    print(x.pow1(2, -2))
    print(x.pow1(3, 5))
    print(x.pow1(100, 0))
    


  61. 31. Write a Python class to reverse a string word by word.
  62. class py_solution:
        def reverse_words(self, s):
            return ' '.join(reversed(s.split()))
    
    
    print(py_solution().reverse_words('hello .py'))
    

    or

    string = "I am a python programmer"
    words = string.split()
    words = list(reversed(words))
    print(" ".join(words))
    
  63. Write a program that opens a file dialog that allows you to select a text file. The program then displays the contents of the file in a textbox.
  64. from tkinter import *
    from tkinter.filedialog import *
    from tkinter.scrolledtext import ScrolledText
    #lab program 2 type
    root = Tk()
    root.title('File dialog') 
    textbox = ScrolledText()
    textbox.grid()
    
    filename=askopenfilename(initialdir='C:\Python_Code\examples',filetypes=[('Text files', '.txt'),('All files', '*')])
    s = open(filename).read()
    textbox.insert(1.0, s)
    mainloop()
    

    or

    from tkinter import *
    from tkinter.filedialog import *
    from tkinter import filedialog
    from tkinter.scrolledtext import ScrolledText
    #lab program 1 type
    master = Tk()
    master.title('File dialog')
    textbox = ScrolledText()
    textbox.grid()
    
    def callback():
        filename=askopenfilename()
        s = open(filename).read()
        textbox.insert(1.0, s)
     
    errmsg = 'Error!'
    bt=Button(text='File Open', command=callback)
    bt.grid(column=1, row=0)
    mainloop()
    


  65. 32. Write a program to demonstrate Try/except/else
  66. try:
        x=int(input('Enter a number upto 100: '))
        if x > 100:
            raise ValueError(x)
    except ValueError: 
        print(x, "is out of allowed range")
    else:
        print(x, "is within the allowed range")
    
    
  67. Write a program to demonstrate try/finally and with/as.

  68. try/finally
    try:
        print('try block')
        x=int(input("Enter a number:"))
        y=int(input("Enter another number:"))
        z=x/y
    except ZeroDivisionError:
        print("except ZeroDivisionError block") 
        print("Division by not accepted")
    else:
        print("else block")
        print("Division = ", z)
    finally:
        print("finally block")
        
    print ("Out of try, except, else and finally blocks." )
    
    Output1:
    try block
    Enter a number:100
    Enter another number:10
    else block
    Division =  10.0
    finally block
    Out of try, except, else and finally blocks.
    
    
    Output2:
    try block
    Enter a number:100
    Enter another number:0
    except ZeroDivisionError block
    Division by not accepted
    finally block
    Out of try, except, else and finally blocks.
    

    with/as
    # file handling
    
    #1)without using with statement
    file=open('123.txt','w')
    file.write('hello world')
    file.close()
    
    #2)with try and finally
    file=open('123.txt','w')
    try:
    	file.write('hello world')
    finally:
    	file.close()
    
    #3)using with statement
    with open('123.txt','w') as file:
    	file.write('hello world') 
    

No comments

JavaFX Scene Builder

  This is an article about the JavaFX Scene Builder. You will get a short introduction about the installation and usage of the software. The...