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

Python lab manual

this is a python hands on for beginners
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
10 views

Python lab manual

this is a python hands on for beginners
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 22
SRK INSTITUTE OF TECHNOLOGY ENIKEPADU, VJAYAWADA, DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING — DATA SCIENCE CaN ‘SRK INSTITUTE OF TECHNOLOGY VIJAYAWADA PYTHON PROGRAMMING LAB (R20ES1203) LAB MANUAL (I B.Tech - I Sem) Regulation: R20 By M. V. SUMANTH Assistant Professor Department of CSE SRK Institute of Technology PYTHON PROGRAMMING LAB (R20ES1203) 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) 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 3) Write a program that uses a for loop to print the numbers 8, 11, 14, 17, 20, ..., 83, 86, 89. 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 number of times. 5) Use a forloop to print a triangle like the one below. Allow the user to specify how high the triangle should be. 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, 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. 8) Write a program that asks the user to enter a word and prints out whether that word contains any vowels. 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 abcdeandABCDE the program should print out AaBbCeDdke. 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. 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. 12) Write a program that generates a list of 20 random numbers between 1 and 100. Python Programming Lab SRK Institute of Technology (a) Print the list. (b) Print the average of the elements in the list. (©) Print the largest and smallest values in the list. (@) Print the second largest and second smallest entries in the list, (@) Print how many even numbers are in the list of the factors 13) Write a program that asks the user for an integer and creates a list that consist of that integer. 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 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]. 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 itis also easier to add new conversions if you use lists. 17) Write a function called sum_digitsthat is given an integer num and returns the sum of the digits of num. 18) Write a function called first_diffthat is given two strings and retums the first location in which the strings differ. If the strings are identical, it should return 1. 19) Write a function called number_of_factorsthat takes an integer and returns how many factors the number has. 20) Write a function called is_sortedthat is given a list and returns True if the list is sorted and False otherwise. 21) Write a function called root that is given a number x and an integer n and returns xI/n. In the function definition, set the default value of n to 2. 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. 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. 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 occurrences of the letter in the user’s word. 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. Python Programming Lab SRK Institute of Technology 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. 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_pricethat 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_purchasethat receives the number of items to be bought and decreases amount by that much. 28) Write a class called Time whose only field is a time in seconds. It should have a method called convert to_minutesthat 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_hoursthat returns a string of hours, minutes, and seconds formatted analogously to the previous method. 29) Write a class called Converter. The user will pass a length and a unit when declaring an object from the class—for example, ¢ = 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. 30) Write a Python class to implement pow(x, n). 31) Write a Python class to reverse a string word by word. 32) 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. 33) Write a program to demonstrate Try/exceptielse. 34) Write a program to demonstrate try/finally and witha Python Programming Lab SRK Institute of Technology 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. Program: k-input("Enter weight in kilograms:") k=int(k) pok#*2.2 print("Given weight in pounds is",p) Output: Enter weight in kilograms: 5 Given weight in pounds is 11.0 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. Program: x=input("Enter first number:") x=int(x) y-int(input("Enter second number:")) z-int(input("Enter third number:")) total=x+y+z, avg=total/3 print("Total of given three numbers is",total) print("Average of given three numbers is Output: Enter first number:20 Enter second numbe Enter third number:35 Total of given three numbers is 70 Average of given three numbers is 23 3) Write a program that uses a for loop to print the numbers 8, 11, 14, 17, 20,..., 83, 86, 89. Program: x-range(8,90,3) for iin x: print(i,end="t") 5 Python Programming Lab SRK Institute of Technology Output: 8 11 14 17 20 23 26 29 32 35 38 41 44 47 50 53 56 59 62 65 68 71 74 77 80 83 86 89 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 number of times. program: name=input("Enter your name:") n=input("How many times you want to print the name:") n=int(n) for i in range(n): print(iH1 name) Output: Enter your name: Sumanth How many times you want to print the name: 5 1 Sumanth. 2 Sumanth 3 Sumanth 4 Sumanth 5 Sumanth 5) Use a forloop to print a triangle like the one below. Allow the user to specify how high the triangle should be. program: h=input("Enter the height of triangle") h=int(h) for k in range(h): for i in range(k+1): print("*",end=" "y Python Programming Lab Output: SRK Institute of Technology Enter the height of triangle6 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. program: Output: import random n-tandom.randint(1,10) n=int(n) while(1); meinput("Guess the number generated between 1 and 10:") m=int(m) ifm—=n: print("well done. your guesss is correct") break else: print("your guesss is not correct") c=input("Do u want make one more try:(y/n)") if on: break Guess the number generated between I and 10:2 your guesss is not correct Do u want make one more try:(y/n)y Guess the number generated between I and 10:8 your guesss is not correct Do u want make one more try:(y/n)n Python Programming Lab SRK Institute of Technology 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. program: Output: ‘x=input("Enter first number:") x-float(x) y=float(input("Enter second number:")) diff-abs(x-y) if diff<=0.001: print("Close") else: print("Not Close") Enter first number:20.5678 Enter second number:20.5679 Close 8) Write a program that asks the user to enter a word and prints out whether that word contains any vowels. Program: Output: word=input("Enter any word: vowel="aeiouAEIOU" 0 for x in word: ifx in vowel: print("The given word contains vowels") c=ctl break ife—0; print("The given word doesn't contains vowels") Enter any word:Python The given word contains vowels Python Programming Lab SRK Institute of Technology 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 Abede and ABCDE the program should print out AaBbCeDdEe. Program: sI=input("Enter first string:") s2=input("Enter Second string:") M=len(s1) 12=Ien(s2) if 12: print("Given strings are not of same length”) else: print("Altemate charatcers of the given two strings: for i in range(I1): print(s1[i]+s2{i],end=") Output: Enter first string:python Enter Second string:PY THON Alternate charatcers of the given two strings: pPyYtThHoOnN, 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. program: n=int(input("Enter a large number:")) print("{:,}"-format(n)) Output: Enter a large number: 1487963487524698 1,487,963 487,524,698 Python Programming Lab SRK Institute of Technology 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*xt+4*y or 3*(x+5). Write a program that asks the user for an algebraic expression and then inserts multiplication symbols where appropriate. program: x=input("Enter algebraic expression:") a(] ien(x) for i in range(n-1): a.append(x[i)) if x[i+1].isalpha() or x[i+1]—=" a.append("*") a.append(x[n-1]) ans=" join(a) print(ans) Output: Enter algebraic expression:2x+Sy-7z, DextSy-T82, 12) Write a program that generates a list of 20 random numbers between I and 100. (a) Print the list. (b) Print the average of the elements in the list. (©) Print the largest and smallest values in the list. (d) Print the second largest and second smallest entries in the list (©) Print how many even numbers are in the list. Program: import random a] for i in range(20): x=random.randint(1,100) a.append(x) print("The elements in list are:") print(a) avg-sum(a)/len(a) print(" Average of the elements in list is {:.2f}"format(avg)) M=max(a) print("Maximum of the elements in list is",M) m=min(a) print("Minimum of the elements in list is".m) asort() 10 Python Programming Lab SRK Institute of Technology print("After soring, the elements in list are:") print(a) SL=a[18]#the size of the list is 20 print("Second largest of the elements in list is",SL) print("Second smallest of the elements in list is",a[1]) count=0 fori ina: ifi%~2—0: count=count#1 print("The number of even elements in the list is" count) Output: ‘The elements in list are: [22, 46, 97, 5, 26, 22, 79, 25, 24, 7, 9, 17, 14, 13, 55, 41, 67, 4, 25, 22] Average of the elements in list is 31.00 Maximum of the elements in list is 97 Minimum of the elements in list is 4 After soring, the elements in list are: [4, 5, 7, 9, 13, 14, 17, 22, 22, 22, 24, 25, 25, 26, 41, 46, $5, 67, 79, 97] Second largest of the elements in list is 79 Second smallest of th -ments in list is 5 The number of even elements in the list is 8 13) Write a program that asks the user for an integer and creates a list that consists of the factors of that integer. program: n-input("Enter a poitive integer") n=int(n) factors-[] for i in range(1n+1): if n%i=0; factors.append(i) print("The factors of {} are:".format(n)) print(factors) Output: Enter a poitive integer20 The factors of 20 are: [1, 2, 4, 5, 10, 20] ca Python Programming Lab SRK Institute of Technology 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. program: import random count=0 a) for iin range(100): x=random.randint(0,1) a.append(x) print("The generated list is print(a) temp-0 for iin a: if i--0: temp=temp+1 else: if temp>count: count=temp temp-0 print("The longest run of zeros is", count) Output: ‘The generated list is: LL, 1,0, 1, 0,0,0, 1,0,0,0,1,1,1,1,1,0,1, 1,0,1,0,1,1,1, 1,1, 1, 1,0, 0,0, 0,1, 1,1, +0, 1,0, 1, 1,1, 1, 1,0,0, 1,0, 1, 1, 1, 1, 1,0, 1,0, 0,0, 0,0, 1, 1, 1, 1,0, 0,1, 1,0, 1, 0, 0 The longest nun of zeros is S 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]. program: 3.4,3,5,2,7,1,9,3,5] ‘lements in the list are:") fori ina: if not in b: bappend(i) print("After removel of duplicates, Elements in the list are:") 12 Python Programming Lab SRK Institute of Technology print(b) Output: Elements in the list are: [2,3,4,3,5, 2,7, 1,9,3, 5] After removel of duplicates, Elements in the list are: [2,3,4,5,7,1,9] 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, you use lists. is much shorter with lists and it is also easier to add new conversions if Program: # Lfeet=12 inches, 3 feets1 yard, 5280 feets=I mile é £= int(input("Enter distance in feet:")) msg-["inches"," yards", "miles"," milli meters","centi meters","meters","kilo meters"] ans=[P*12,f13,175280,0*304.8,030.48, P*0,3048,F*0,0003048] while(1): ") print("I:convert distance to inches") print("2:convert distance to yards") print("3:convert distance to miles") print("4:convert distance to milli meters") print("S:convert distance to centi meters") print("6:convert distance to meters") print("7:convert distance to kilo meters") print("S:exit") k-input("“choose the option for conversion from menu:") print ") k=intk) if k not in (1,2,3,4.5,6,7]: break else: print("Converted distance .ans{k-1],msgfk-1]) Output: Enter distance in feet:6 13 Python Programming Lab I :convert distance to inches 2:convert distance to yards 3:convert distance to miles 4:convert distance to milli meters S:convert distance to centi meters 6:convert distance to meters T-convert distance to kilo meters Bcexit choose the option for conversion from menu: 1 Converted distance is 72 inches I:convert distance to inches 2:convert distance to yards 3:convert distance to miles 4-convert distance to milli meters S:convert distance to centi meters 6:convert distance to meters T-convert distance to kilo meters B:exit choose the option for conversion from menu:5 Converted distance is 182.88 centi meters I:convert distance to inches 2:convert distance to yards 3:convert distance to miles 4:convert distance to milli meters S:convert distance to centi meters 6:convert distance to meters T-convert distance to kilo meters B:exit choose the option for conversion from menu:8 Python Programming Lab SRK Institute of Technology 14 SRK Institute of Technology 17) Write a function called sum_ the digits of num. program: that is given an integer num and returns the sum of def sum_digits(m): ans=0 while m>0: m%10 m=m//10 ans=ans+r return ans n=input("Enter an integer:") n=int(n) ans~sum_digits(n) print("Sum of the digits of {} is {}"format(n,ans)) Output: Enter an integer:246 Sum of the digits of 246 is 12 18) Write a function called first_diffthat is given two strings and returns the first location in which the strings differ. If the strings are identical, it should return -1. Program: def first_difits1,s2): ans=1 n=len(s!) for i in range(n): if s1fi}!s2fi]: ans=i break return ans x=input("Enter first string:") y=input("Enter second string:") d-first_difi(x,y) if¢=1 print("Given strings are equal”) else’ print("Location number at which strings differ for first time is",d-1) Output: Enter first string:-Ramu Enter second string:Ravi Location number at which strings differ for first time is 3 Python Programming Lab SRK Institute of Technology 19) Write a function called number_of_factors that takes an integer and returns how many factors the number has. program: def number_of_factors(m): count=( for i in range(1,m+1): ifm%i—0: count+=1 — #feount=count+] return count n-input("Enter a positive integer:") n=int(n) ans=number_of_factors(n) print("Number of factors of {} is {}".format(n,ans)) Output: Enter a positive integer:40 Number of factors of 40 is 8 20) Write a function called is_sorted that is given a list and returns True if the list is sorted and False otherwise. program: def is_sorted(a): n-len(a) for i in range(n-1): if afi}>afi+ 1): ans-False break else: ans=True return ans a=[20,30,12,50] b-[10,20,30,40] ans=is_sorted(b) if ans—True: print(""The list is sorted") else: print("The list is not sorted") Output: The list is sorted Python Programming Lab 16 SRK Institute of Technology 21) Write a funetion 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. Program: Output: def root(x, n=2): ans=pow(x,(1/n)) ans-round(ans) return ans x=input("Enter a number for base:") x=int(x) ‘n=int(input("Enter an integer for nth root power:")) ytoot(x,n1) zt00t(x) print("{}th root of {} is {}".format(n,x,y)) print("square root of {} is {}"format(x,z)) Enter a number for base: Enter an integer for nth root power:5 Sth root of 32 is 2 square root of 32 is 6 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. Program: def prime(m): for i in range(2,m): if m%i—=0: return 0 else: return 1 def first_n_primes(n=100): count=0 m2 primes=[] while(1); if prime(m): primes.append(m) count'=1 return primes 17 Python Programming Lab Output: SRK Institute of Technology n=int(input("Enter value for n:")) ans=first_n_primes(n) print("First {} prime numbers are:".format(n)) for i in ans: print(izend="\ ans=first_n_primes() print() print("First 100 prime numbers are:") for i in ans: print(iend="t") Enter value for n: 10 First 10 prime numbers are: 2093 5 7 Mo 1 17 19 23 29 First 100 prime numbers are: 2 3 5 7 WN 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 ISL 157 163 167 173 179181 191 193 197 199 211-223-227 -229«-233-«239-«241_-«-251-—-257 263 269 © -271:«277:«281:«-283 «293 307-311-313. «317 «331.337 347 349 353-359 367-373. «379-383 389 397 401 409 419 421 431 433 439 443. 449.457 461 463 «467 «479487491 499 503 509 S21 $23 S41 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. Program(a): def merge(a,b): c=a+b csort() return ¢ n=int(input("Enter number of elements in first list") ~{] for i in range(n): x=input("enter element:") x=int(x) a.append(x) n=int(input("Enter number of elements in second list") b-{) for i in range(n): x-input("enter element:") 18 Python Programming Lab SRK Institute of Technology x=int(x) baappend(x) ans=merge(a,b) print("Elements after merging two lists:") for i in ans: print(i,end="\t") Output: Enter number of elements in first list5 enter element:3 enter element:7 enter element:9 enter element:2 enter element:6 Enter number of elements in second list4 enter element:1 enter element:7 center element:4 enter element:9 Elements after merging two lists: 12 3 4 677 9 9 Program23(b): def merge(a for x inb: for i in range(len(a)): if afi} continue else: a.insert(ix) break else: a.append(x) return a a=[10,20,30,56] b=[5,15,45,65,89] ans=merge(a,b) print("Elements after merging two lis for i in ans: print(i,end="\t") Output: Elements after merging two lists:$ 10 15 20 30 45 56 6589 19 Python Programming Lab SRK Institute of Technology 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 occurrences of the letter in the user’s word. Program: from itertools import permutations import enchant d-enchant Dict("en_US") word-input("Enter a word:") n-len(word) ans=[] for i in range(2,n): for x in permutations(word,i) w=" join(x) ans.append(w) ans=set(ans) ans-list(ans) final_ans=[] for w in ans: if d.check(w): final_ans.append(w) print("Smaller words using letters of given word are:") print(final_ans) 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. Program: fopen(‘emails.txt’) print("The email addreses in the file are:") lines=f.readlines() for line in lines: ine.strip() print(line,end="') Tin Output: ‘The email addreses in the file are: [email protected];[email protected];[email protected]; 20 Python Programming Lab SRK Institute of Technology 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 Program: Output: f1=open(‘temp_degs.txt’) £2 = open("temp_fahr.txt", "w") forx in fl x=x.stripQ) x=int(x) x=(x*1.8)132 x=str(x) £2.write(x) f2.write("\n") fl.close() f2.close() £2-open(‘temp_fabr.txt’) print("Temperatures in fahrenheit file are:") for x in f2: print(x,end=' ‘Temperatures in fahrenheit file are: 50.0 53.6 59.0 68.0 710 30) Write a Python class to implement pow(x, n). Program: Python class prog30: def power(self;x,n) ans=I for i in range(n): ans=ans*x return ans =int(input("Enter base value:")) n= int(input("Enter power value:")) ans=prog30().power(b,n) print(" Answer is",ans) 21 Programming Lab SRK Institute of Technology 31) Write a Python class to reverse a string word by word. Program: class prog31: def str_rev(self.s): ans~’'join(reversed(s.split())) return ans x-input("Enter a statement:") print('reverse of the given string word by word is’) ans=prog31().stt_rev(x) print(ans) 22 Python Programming Lab

You might also like