You are on page 1of 27
Python Basics Practice ‘Thu Huong Nguyen! and Si Thin Nguyen? Anthuong@vku.udn.on 2nsthin@uku.udn.om 12Paculty of Computer Science, VKU 1 Exercises with solution 1.1 Write a Python program which accepts a number from the users and check it even or odd, print out an appropriate message to the user. (1); {mum = intGnput ("Enter a number: ")) mod = num 2 if mod > 0 print ("This is an odd number.") else: print("This is an even nunber.") Enter a number: 9 This is an odd number. 1.2 Write a Python program to solve a quadratic equation ax? + be + (2): [import math a = int (input! ) b = int (input ("b=") ¢ = int (input! ) # If a is 0, then incorrect equation if a==0 print ("Input correct quadratic equation") else: # calculating discriminant using formula dis=b+b-4+are sqrt_val = math. sqrt (abs (dis)) # checking condition for discriminant if dis > 0: print(" real and different roots ") print((-b + sqrt_val)/(2 + a)) print((-b - sqrt_val)/(2 * a)) elif dis == 0: print(" real and sane roots") print(-b / (2 + a)) # when discriminant is less than 0 else print("Complex Roots") print(- b/ @* a), "+i", sqrt_val) print(. b / (2* a), "- i", sqrt_val) an Complex Roots “1.0 + 4 4.s9s9794a5se6356 “1.0 - 4 4.89g979485566356 1.3 Write a program that reads a positive integer, n, from the user and then displays the sum of all of the integers from 1 to n. The sum of the first n positive integers can be computed using the formula: sum = “o+) Python includes a built-in function named sum. [3]: # Read the value of m from the user n= int(input("Enter a positive integer: ")) # Compute the sum sm=n+* (n+ 1) /2 # Display the result print("The sun of the first", n, "positive integers is", sm) Enter a positive integer: 8 The sum of the first 8 positive integers is 36.0 1.4 Write a program that reads two integers, a and b, from the user. The program will compute and display: - The sum of a and b - The difference when b is subtracted from a - The product of a and b - The quotient when a is divided by b - The remainder when a is divided by b - The result of logl0 a - The result of ab Hint: Use the log10 function in the math module helpful for computing the second last item in the list. [4]: [from math import logio # Read the input values from the user a = int(input("Enter the value of a: ")) b = int (input ("Enter the value of b: ")) # Conpute and display the sun, difference, product, quotient and remainder print(a, "#", b, "is", a + b) print(a, "-", b, "is", a - b) print(a, "4", b, "is", a+ b) print(a, "/", b, "is", a/b) print(a, "Z", b, "is", a % b) # Compute the logarithm and the pouer print("The base 10 logarithm of", a, "is", 1ogi0(a)) print(a, "“", b, "is", a¥*b) Enter the value of a: § Enter the value of b: 6 +6 is it - 6 is -1 * 6 is 30 / 6 is 0.8333333333333334 46 iss The base 10 logarithm of 5 is 0.6989700043360189 5° 6 is 15625 1.5 Write a Python program that determines how quickly an object is travelling when it hits the ground. The user will enter the height from which the object is dropped in meters (m). Because the object is dropped its initial speed is 0 m/s. Assume that the acceleration due to gravity is 9.8m/s2. Use the formula vf = /(u? +2ad) to compute the final speed,vf , when the initial speed, v , acceleration, a, and distance, d, are known. [5]: (from math import sqrt # Define a constant for the acceleration due to gravity in m/s+2 GRAVITY = 9.8 # Read the height from which the object is dropped = float(input ("Height (in meters): ")) # Compute the final velocity vf = sqrt(2 * GRAVITY * 4) # Display the result print("It will hit the ground at %.2f a/s." % vf) Height (in meters): 806 Tt will hit the ground at 125.69 m/s. 1.6 Write a Python program that begins by reading a number of seconds from the user. The program will display the equivalent amount of time in the form DD : HH : MM : SS, where D, HH, MM, and SS represent days, hours, minutes and seconds respectively. The hours, minutes and seconds are all formatted in exactly two digits. (6): # Convert a nunber of seconds to days, hours, minutes and seconds SECONDS_PER_DAY = 86400 SECONDS_PER_HOUR = 3600 SECONDS_PER_MINUTE = 60 # Read the duration from the user in seconds seconds = int (input ("Enter a number of seconds: ")) # Compute the days, hours, minutes and seconds days = seconds / SECONDS_PER_DAY seconds = seconds % SECONDS_PER_DAY hours = seconds / SECONDS_PER_HOUR seconds = seconds % SECONDS_PER_HOUR minutes = seconds / SECONDS_PER_MINUTE seconds = seconds % SECONDS_PER_MINUTE # Display the result with the desired formatting print("The equivalent duration is","%{4:1024:/024:#/024." % (days, hours, minutes, seconds)) Enter a number of seconds: 478456 The equivalent duration is §:12:5% 116. 1.7 Write a Python program which accepts a string and replacing all occur- rences of its first char have been to ‘#", except the first char itself. Ex: ‘tutor’ —> ‘tutor? [7]: /stri = input ("Enter a string: ") char = stri[0) stri = stri-replace(char, '#') stri = char + stri(i:] print('The ney string after replacing:' + str1) Enter a string: tutor The new string after replacing: tutor 1.8 Write a Python program and count all letters, digits, and special symbols from a string given by the users Use the following built-in string functions isalpha(): To check if a string/character is an alphabet isdigit(): To check if a string/character is a digit. (8): [stri = input(“Enter a string: char_count = 0 (9) digit_count = symbol_count for char in stri if char. isalpha(): char_count += 1 elif char. isdigit() digit_count += 1 # if it is not Letter or digit then it is special symbol else: symbol_count += 1 print("total counts of chars, Digits print("Chars =", char_count, "Digits = and symbols \n") » digit_count, "Symbol =", symbol_count) Enter a string: hello vkuer total counts of chars, Digits, and symbols Chars = 10 Digits = 0 Symbol = 1 1.9 Write a Python program in which it will begun by reading the cost of a meal ordered at a restaurant from the user. Then the program will compute the tax and tip for the meal. Use the local tax rate 5% when computing the amount of tax owing. Compute the tip as 18% of the meal amount (without. the tax). The output from the program should include the tax amount, the tip amount, and the grand total for the meal including both the tax and the tip. Format the output so that all of the values are displayed using two decimal places. # Compute the tas and tip for a restaurant meal. TAK_RATE = 0. TIP_RATE = 0.18 # Read the cost of the meal from the user cost = float(input ("Enter the cost of the meal: ")) # Compute the taz and the tip tax = cost * TAX RATE tip = cost + TIP_RATE total = cost + tax + tip # Display the result print("The tax is %.2f and the tip is %.2f, making the", "total %.2f"% tax, tipsy total) Enter the cost of the meal: 250000 The tax is %.2f and the tip is %.2f, making the total 12500.00 45000.0 307500.0 1.10 Write a Python program to split a string given by the users on hyphens and display each substring. Use the string funetion split() to] uty (21 stri = input (“Enter a string: ") # split string by the symbol '-' sub_strings = str1.split( print("Displaying each substring:") for sub in sub_strings: print (sub) Enter a string: Hello - VUer Displaying each substring: Hello viUer 1.11 Write a Python program that reads a letter of the alphabet from the user. If the user enters a,e,i,0 or u then the program will display a message indicating that the entered letter is a vowel. If the user enters y then the program will display a message indicating that sometimes y is a vowel, and sometimes y is a consonant. Otherwise the program will display a message indicating that the letter is a consonant. # Determine if a letter is a vowel or a consonant # Read a Letter from the user letter = input("Enter a letter: ") # Classify the Letter and report the result if letter —= "a" or letter == "e" or letter == "i" or letter == "o" or letter print("It?s a vowel.") elif letter == "y": print("Sometimes it’s a vowel... Sometimes it’s a consonant.) else: print ("It’s a consonant. ") Enter a letter: 0 It’s a vowel. 1.12 Write a Python program accepting the name of a month from the user as a string. The program will display the number of days in that month. ‘The length of a month varies from 28 to 31 days except to display “28 or 29 days” for February. # Display the nunber of days in a month. # Read the month name from the user month = input("Enter the name of a month: ") # Compute the nunber of days in the month days = 31 if month == "April" or month == "June" or month == "September" or month ==, Mlovember": days = 30 elif month == "February": days = "28 or 29" U3) # Display the result print(month, "has", days, "days in it.") Enter the name of a month: September September has $0 days in it. 1.13 Write a Python program accepting the lengths of the three sides of a triangle from the user. Then display a message that states the triangle’s type. The classification of triangles is based on classified based on the lengths of its sides as equilateral, isosceles or scalene. All three sides of an equilateral triangle have the same length. An isosceles triangle has two sides that are the same length, and a third side that is a different length. If all of the sides have different lengths then the triangle is scalene. # Classify a triangle based on the Lengths of its sides. # Read the side lengths from the user side1 = float(input("Enter the length of side 1: ")) side2 = float(input("Enter the length of side 2: ")) side3 = float(input("Enter the length of side 3: ")) # Determine the triangle’s type Af sidel == side2 and side? == sided: tri_type = "equilateral" elif side1 == side? or side2 == side3 or \ side3 == sidet: tri_type = "isosceles" else ‘tri_type = "scalene" # Display the triangle’s type print("That’s a", tri_type, "triangle") Enter the length of side 1: 25 Enter the length of side 2: 36 Enter the length of side 3: 25 That’s a isosceles triangle 1.14 Write a Python program accepting a year from the user and displays the animal associated with that year. The program will work correctly for any year greater than or equal to zero, not just the ones listed in the table. Year Animal 2000 Dragon 2001 Snake 2002 Horse 2003 Sheep 2004 Monkey 2005 Rooster 2006. Dog, ua) Year Animal 2007 Pig 2008 Rat. 2009 Ox 2010 Tiger 2011 Hare # Determine the animal associated with a year according to the Chinese zodiac. # Read a year from the user year = int(input("Enter a year: ")) # Determine the animal associated with that year if year % 12 == 8: animal = "Dragon" elif year % 12 animal = "Snake" elif year % 12 == 10: aninal = "Horse" elif year % 12 == 11: animal = "Sheep" elif year % 12 == 0: animal = "Monkey" elif year % 12 animal = "Rooster" elif year % 12 == 2: animal = "Dog" elif year % 12 = 3 animal = "Pig" elif year % 12 animal = "Rat" elif year % 12 animal = "Ox" elif year % 12 = 6 animal = "Tiger" elif year 12 = 7 animal = "Hare" 5 # Report the result print("/d is the year of the is." % (year, animal) Enter a year: 2022 2022 is the year of the Tiger. ts] 1.15 Write a Python program accepting a month and day from the user. The user will enter the name of the month as a string, followed by the day within the month as an integer. Then the program will display the season associated with the date that was entered. The first days of season include March 20 (Spring); June 21 (Summer); September 22 (Fall); December 21 (Winter) # Determine and display the season associated with a date. # Read the date from the user month = input("Enter the name of the month: ") day = int(input ("Enter the day number: ")) # Determine the season if month == "January" or month season = "Winter" elif month == "March": if day < 20 February" season = "Winter" else: Pesconeatsoetned elif month == "April" or month == "May": season = "Spring" elif month == "June": if day < 21 season = "Spring" else: season = "Sunner" elif month == "July" or month “august season = "Sumner" elif month == "September" if day < 22: season = "Sunner" else! season = "Fall" elif month == "October" or month =: season = "Fall" elif month if day < 21 season = "Fall" else: November": season = "Winter" # Display the result print(month, day, "is in", season) Enter the nane of the month: September Enter the day number: 23 September 23 is in Fall (16) uz 1.16 Write a Python program using a for loop and the range() function to display all of the positive multiples of 3 up to (and including) a value entered by the user. # Read the limit from the user Limit = intCinput ("Enter an integer: ")) # Display the positive miltiples of 3 up to the Limit print("The multiples of 3 up to and including", limit, "are:") for i in range(3, limit + 1, 3): print (i) Enter an integer: 6 The multiples of 3 up to and including 6 are: 3 6 1.17 A particular cinema determines the price of admission based on the age of the guest. Guests 2 years of age and less are admitted without charge. Children between 5 and 12 years of age cost 50000dong. Seniors aged 65 years and over cost 150000 dong. Admission for all other guests is 230000 dong. Write a Python program that begins by reading the ages of all of the guests in a group from the user, with one age entered on each line. ‘The user will enter a blank line to indicate that there are no more guests in the group. Then the program will display the admission cost for the group with an appropriate message. # Compute the admission price for a group to go to the cinema. # Store the admission prices as constants BABY_PRICE = 0 CHILD_PRICE = 50000 ADULT_PRICE = 230000 SENIOR_PRICE = 150000 # Store the age Limits as constants BABY_LIMIT = 4 CHILD_LIMIT ADULT_LIMIT # Create a variable to hold the total admission cost for all guests total = 0 # Keep on reading ages until the user enters a blank Line Line = input("Enter the age of the guest (blank to finish): ") while line != ‘age = int (Line) # Add the correct amount to the total if age <= BABY_LIMIT: total = total + BABY_PRICE elif age < CHILD_LIMIT total = total + CHILD_PRICE elif age <= ADULT_LIMIT 10 us) total = total + ADULT_PRICE else: total = total + SENIOR_PRICE # Read the nest age from the user Line = input ("Enter the age of the guest (blank to finish): ") # Display the total due for the group, formatted using two decimal places print("The total for that group is " , total, " dong") Enter the age of the guest (blank to finish): 36 Enter the age of the guest (blank to finish): 89 Enter the age of the guest (blank to finish): 4 Enter the age of the guest (blank to finish): The total for that group is 380000 dong 1.18 Write a Python program that displays a multiplication table as follows: 45 67 8 9 0 3 34°56 7 8 9 0 6 8 1 2 MM 16 18 20 9 12 15 18 2 24 27 30 8 12 16 20 24 28 32 36 40 15 20 25 30 35 40 45 50 12 18 24 30 36 42 48 54 60 14 21 28 35 42 49 56 63 70 16 24 32 40 48 56 64 72 80 18 27 36 45 54 63 72 81 90 10 10 20 30 40 50 60 70 80 90 100 # Display a multiplication table for 1 times 1 through 10 times 10 MIN = 1 MAX = 10 # Display the top row of labels print(" ", end="") for i in range(MIN, MAK + 1): print ("l4a" % i, end") print # Display the table for i in range(MIN, MAK + 1): print ("/4a" % i, endo") for j in range(MIN, MAX + 1): print ("/4a" 1 1 * 3), end="") print 128 45 6 7 & 9 10 34 5 6 7 8 9 10 2 2 4 6 8 10 12 14 16 18 20 9 12 15 18 21 24 27 30 ul 8 12 16 20 24 28 32 36 40 10 15 20 25 30 35 40 45 50 12 18 24 30 36 42 48 54 60 14 21 28 35 42 49 56 63 70 16 24 32 40 48 56 64 72 80 18 27 36 45 54 63 72 81 90 20 30 40 80 60 70 80 90 100 Seavoae 1.19 Write a Python program to construct the following pattern, using a nested for loop. Cig): [n=5; for i in range(n): for j in range(i): print ('# ', end="") print('") for 4 in range(n,0,~ for j in range(i): print('* ', en print('") 2 (20) (21) 1.20 Write a Python program to clone or copy a list. original_list = [10, 22, 44, 23, 4] new_list = list(original_1ist) print (original_list) print (new_list) [10, 22, 44, 23, 4] (10, 22, 44, 23, 4] 1.21 Write a Python program to remove duplicates from a list. The list is created by the words from the user until the user enters a blank line. After the user enters a blank line the program will display each word entered by the user exactly once. The words should be displayed in the same order that they were first entered. Example: The user enters: Hello VKUer Hello to VKUer Python Output: Hello VKUer to Python # Read words from the user and store them in a list words = 1] word = input ("Enter a word (blank line to quit): ") while vord != "" # Only add the word to the list tf # it is not already present in it if word not in vords: ‘words append (word) # Read the next word from the user word = input("Enter a word (blank line to quit): ") # Display the unique words for word in vords print (word) Enter Enter Enter Enter Enter word (blank line to quit): Hello word (blank line to quit): VkUer word (blank line to quit): Hello word (blank line to quit): to word (blank line to quit): VéUer peepee 13 (22) (23) Enter a word (blank line to quit): Python Enter a word (blank line to quit) Hello vaUer to Python 1.22 Write a Python program to append a list to the second list. listi = 1, 2, 3, 01 List2 = ['Red", ‘Green’, 'Black'] final_list = list + list2 print (final_list) (1, 2, 3, 0, ‘Red’, ‘Green’, 'Black"] 1.23 Write a Python program to rearrange the elements in a list. The list is created by the words from the user until the user enters a blank line. After the user enters a blank line the program will display each word entered by the user exactly once. # Create a new, empty List values = (] # Read values from the user and store them in a List until a blank line isy entered Line = input("Enter a number (blank line to quit): ") while line != "" num = float (Line) values. append (nun) line = input ("Enter a number (blank line to quit) # Sort the values into ascending order values. sort() # Display the values for v in values: print (v) Enter a number (blank line to quit): Enter a number (blank line to quit): Enter a number (blank line to quit): Enter a number (blank line to quit): Enter a number (blank line to quit): 3.0 4.0 6.0 8.0 wane u (2a) (28) (26) 1.24 Write a Python program to convert a list of multiple integers into a single integer Example: Sample list: [24,96,50] Output: 243650 Hint: Use the function join() L = (24, 36, 50] print("Original List: ",L) x = int". join(map(str, L))) print("Single Integer: ",x) Original List: [24, 36, 50] Single Integer: 243650 1.25 Write a Python program to create a dictionary and display all of the keys and values with nice formating Example: Sample dictionary: fruit={“banana”: 20000, “apple”: 45000, “orange”: 35000, “grape 60000} Output: The price of banana is 20000 The price of apple is 45000 # Create a dictionary fruit = {"banana": 20000, "apple": 45000, "orange": 35000,"grape": 60000} # Print all of the keys and values with nice formatting for k in fruit print ("The price of", k, "is", fruit(k]) The price of banana is 20000 The price of apple is 45000 The price of orange is 35000 The price of grape is 60000 1.26 Write a Python program to sort a dictionary by its value. import operator fruit = {"banana": 20000, "apple": 45000, "orange": 35000,"grape": 60000} print('Original dictionary : ',fruit) sorted_fruit = sorted(fruit.itens(), key-operator. itengetter(1)) print(Dictionary in ascending order by value : ',sorted_fruit) sorted_fruit = dict( sorted(fruit.itens(), key-operator ~itengetter(1) ,reverse=True)) print('Dictionary in descending order by value : ',sorted_fruit) Original dictionary : {"banana': 20000, ‘apple "grape': 60000} Dictionary in ascending order by value : [(‘banana', 20000), ‘orange’, 35000), apple’, 45000), ('grape’, 60000)1 Dictionary in descending order by value : {'grape': 60000, ‘apple’: 45000, ‘orange’: 35000, 'banana': 20000} 45000, 'orange': 36000, 15 (ar) (28) (291 1.27 Write a Python program to concatenate dictionaries into a new one ‘banana 20000, pple": 45000, "orange": 35000, "grapé 60000} dic2={"strauberry": 200000, "blueberry": 350000, "kiwi": 250000} dic3-{"waterlenon": 37000, "peach": 24000, "pineapple": 39000} dicd = 0 for d in (dict, dic2, dicd): dic4. update a) print (died) {'banana': 20000, ‘apple': 45000, ‘orange’: 35000, ‘grape’: 60000, ‘strawberry’: 200000, "blueberry': 350000, 'kiwi': 250000, ‘waterlemon': 37000, 'peach': 24000, ‘pineapple’: 39000} 1.28 Write a Python program to remove a key from a dictionary. The users enter a key that they want to remove. fruit -{"banana": 20000, “apple”: 45000, "orange": 35000, "grape": 60000} print (fruit) # Read key from the user key = input("Enter a key: ") if key in fruit: del fruit [key] print fruit) {"banana': 20000, ‘apple': 45000, ‘orange’: 35000, ‘grape’: 60000} Enter a key: orange {'banana': 20000, ‘apple’: 45000, "grape': 60000} 1.29 Write a Python program to create a tuple with empty elements/ with different data types/ with numbers and print one item ‘#Create an empty tuple 2-0 print (x) #Create an empty tuple with tuple() function built-in Python tuplex - tuple( print (tuplex) #Create a tuple with different data types tuplex = ("tuple", False, 3.2, 1) print (tuplex) #Create a tuple with numbers tuplex = 5, 10, 15, 20, 25 print (tuplex) #Create a tuple of one item tuplex = 5, print (tuplex) oO oO 16 [30] (31) (tuple', False, 3.2, 1) (5, 10, 15, 20, 25) 6) 1.30 Write a Python program to add an item in a tuple/to reverse a tuple/ to convert a tuple to a list/ to convert a list of tuples to individual lists/ to convert a list of tuples to a dictionary #ereate a tuple tuplex = (4, 6, 2, 8, 3, 1) print (tuplex) #tuples are immtable, so ue can not add new elements fusing merge of tuples with the + operator we can add an element and it willy cereate a new tuple tuplex = tuplex + (9,) print (tuplex) fading items in a specific index tuplex = tuplex(:5] + (15, 20, 25) + tuplex(:5] print (tuplex) # Reversed the tuple rev_tuplex = reversed(tuplex) print (tuple (rev_tuplex)) fconverting the tuple to List Listx = List (tuplex) # create a list of tuples 2= 00x", 1), Ce", 2, Cx", 3), Cyt, D, Cy, 2, C2", 1 Acoverting a List of tuples into individual Lists Listi-List(zip(1)) print (list1) fconverting a List of tuples to a dictionary a-0 for a, b in 1: 4.setdefault(a, []).append(b) print (a) (4, 6, 2, 8, 3, 1) (4, 6, 2, 8, 3, 1, 9) (4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3) (3, 8, 2, 6, 4, 25, 20, 15, 3, 8, 2, 6, 4) x ty, ty, 2, G, 2,3, 1,2, 91 ty G21, t2t: GF 1.31 Write a Python program to find the repeated items of a tuple foreate a tuple tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7 print (tuplex) Breturn the number of times it appears in the tuple 7 count = tuplex.count (2) print (count) (2,4, 5, 6,2,3,4,4, 7) 2 1.32 Write a Python program to create a set (32); [print ("Create a new set:") x= set print (x) print (type(x)) print("\nCreate a non empty set:") n= set([0, 1, 2, 3, 41) print (a) print (type(n)) print("\nUsing a literal:") a = {1,2,3, ‘foo! bar'} print (type(a)) print (a) Create a new set: set() Create a non empty set: 40, 1, 2, 3, 4) Using a literal: {1, 2, 3, "bar", 'foo'} 1.33. Write a Python program to remove item(s) from a given set. Use the function pop(). [33]: /mum_set = set([0, 1, 3, 4, 81) print("Original set:") print (num_set) # renove an item froma given set num_set..pop() print("\nAfter removing the first elenent from the said set:") print (num_set) Original set: 40, 1, 3, 4, 5} 18 [4] (35) After removing the first elenent from the said set 4, 3, 4, 5} 1.34 Write a Python program to create set difference. Use the function difference() setel = set({"nango", "orange"]) setc2 = set(("orange", "banana"]) print("Original sets:" print (setc1) print (sete2) ri = setct.difference(setc2) print("\nDifference of setci - setc2:") print (rt) 12 = setc?.difference(setc1) print("\nDifference of setc2 - setct:") print (x2) Original sets: {'mango', ‘orange'} {"banana', ‘orange'} Difference of setcl - sete? {'mango'} Difference of setc2 - setcl: {banana'} 1.35 Write a Python program to create a symmetric difference. Example: The symmetric difference of the sets {1,2,3} and {3,4} is {1,2,4) Use the function symmetric_difference(). setci = set(["mango", "banana"]) setc2 = set(["banana", "orange"]) print("Original sets:") print (sete!) print (setc2) ri = setcl.symmetric_difference(setc2) print("\nSynmetric difference of setci - setc2:") print (rt) 12 = setc2. synmetric_difference(setc1) print("\nSymmetric difference of setc2 - setcl: print (12) setnt = set([1, 1, 2, 3, 4, 5]) setn2 = set([1, 5, 6, 7, 8, 9]) print("\nOriginal sets print (setn1) 19 print (setn2) ri = setnt.symmetric_difference(setn2) print("\nSynmetric difference of setni - setn2:") print (rt) 12 = setn2. synmetric_difference(setnt) print("\nSymmetric difference of setn2 - setn1: print (x2) Original sets: {'banana’, ‘mango'} {/banana', ‘orange'} Symmetric difference of setcl - setc?: {'mango', ‘orange'} Symmetric difference of sete? - setct: {'mango', ‘orange'} Original sets: 4, 2, 3, 4, 5) 1, 5, 6, 7, 8, 9} Symnetric difference of setni - setn2: 42, 3, 4, 6, 7, 8, 9} Symmetric difference of setn2 - setni: 42, 3, 4, 6, 7, 8, 9 1.36 Write a Python program to check if a set is a subset of another set Use the function issubset() [36]; [print ("Check if a set is a subset of another set, using comparison operators and, issubset():\n") setx = set(["apple", "mango"]) sety = set(["mango", "orange"]) setz = set(["mango"]) print("x: ",setx) print(ty: ",sety) print("2: ",setz,"\n") print("If x is subset of y") print(setx <- sety) print (setx. issubset (sety)) print("If y is subset of x") print(sety <= setx) print (sety.issubset (setx)) print("\nIf y is subset of 2") print (sety <= setz) print (sety. issubset(setz)) print("If 2 is subset of y") print(setz <- sety) print (setz.issubset(sety)) Check if a set is a subset of another set, using comparison operators and issubset () x: {'apple', ‘mango'} y: {'mango', ‘orange'} 2: {'mango'} If x is subset of y False False If y is subset of x False False If y is subset of z False False If z is subset of y True True 1.37 Write a Python function to sum all the numbers in a list Example: Sample List : 9, 1, 2, 0,8 Expected Output : 20 [37]: def sum(numbers) total = 0 for x in numbers total += x return total print(sum((9, 1, 3, 0, 7))) 20 1.38 Write a Python function to reverse a string Example: Sample String : “Hello VK Eapected Output : “UKV olleH (38): (def string_reverse(stri) au retri = index = 1en(str1) while index > 0 rstri += strif index - 1 ] index = index - 1 return rstri print (string reverse(‘Hello VKU')) UAV ole 1.39 Write a Python function that takes a list and returns a new list with unique elements of the first list. Example: Sample List : [1,2,3,3,3,3,4,5] Expected Output : [1, 2, 3, 4, 5] (39): (def unique list (1): x0 for a in 1: if a not in x: x. append(a) return x print (unique_list([1,2,3,3,3,3,4,5])) U, 2, 3, 4, 5] 1.40 Write a function that takes three numbers as parameters, and returns the median value of those parameters as its result. Include a main program that reads three values from the user and displays their median. [40]: [## Compute the median of three values using if statements # Oparam a the first value # @param b the second value # Oparam c the third value # Oreturn the median of values a, b and c ‘ def median(a, b, ©) if acb and bcc or a>b and b> ¢ return b if bea and acc or bea and a> ¢ return a if ca and b> ¢ return ¢ ## Compute the median of three values using the min and maz functions and a, little bit of # arithmetic 22 (an) (42) # param a the first value # param b the second value # param c the third value # @return the median of values a, and c ’ def alternatetedian(a, b,c): return arb+c- min(a, b, ¢) - max(a, b, ¢) # Display the median of 3 values entered by the user def nain(): float (input ("Enter the first value: ")) float (input ("Enter the second value: ")) Z = float (input ("Enter the third value: ")) print (*The median value is:", median(x, y, z)) print("Using the alternative method, it is:", alternateledian(x, y, 2)) # Call the main function mainQ Enter the first value: 3 Enter the second value: 5 Enter the third value: 85 The median value is: 5.0 Using the alternative method, it is: 5.0 1.41 Write a Python function to read an entire text file def file_read(éname) : txt = open(fname) print(txt.read()) file_read('sample.txt') Project Jupyter is a community run project with a goal to "develop open-source software, open-standards, and services for interactive computing across dozens of programming languages". It was spun off from IPython in 2014 by Fernando Pérez and Brian 1.42 Write a Python function to read first n lines of a text file def file read_fron_head(fnane, nlines): from itertools import islice with open(fname) as f for line in islice(f, nlines) print (Line) #ile_read_fron_head('sample.txt',1) Project Jupyter is a community run project with a goal to "develop open-source software, open-standards, and services for interactive computing across dozens of programming languages". 23 (43) [4a] 1.43 Write a Python function to find the longest words in a text file def longest_vord(filenane) with open(filename, 'r') as infile: words = infile.read() .split() max_len = len(max(words, key-len)) return [word for word in words if len(word) max_len] print (longest_vord('sample.txt')) Copen-standards, '] 1.44 Write a Python program to read the file name from the user and display the a meaningful error message and request to reenter when the user provided the name of a file that did not exist. # Read the file name from the user fname = input("Enter the file name: ") file_opened = False while file_opened == False # Attempt to open the fite try inf = open(fname, "r") file_opened = True txt = open(fname) print (txt.read()) except FileliotFoundError: # Display an error message and read another file nane if the file was not h opened successfully print("The file name was not found. Please try again.) fname = input ("Re-enter the file nane: ") Enter the file name: dample.txt The file name vas not found. Please try again. Re-enter the file name: sample.txt Project Jupyter is a community run project with a goal to "develop open-source software, open-standards, and services for interactive computing across dozens of programming languages". Tt was spun off from IPython in 2014 by Fernando Pérez and Brian ry 2 Do it yourself 2.1 Write a Python program to compute the area of a triangle. The area of a triangle can be computed using the following formula, where b is the length of the base of the triangle, and h is its height: area = =". The program allows the user to enter values for b and h. The program will then compute and display the area of a triangle with base length b and height h. Hint: Use the math module 2.2 Write a Python program to compute the distance between two points on the Earth. The program allows the user to enter the latitude and longitude of two points on the Earth in degrees. The program will display the dis- tance between the points, following the surface of the earth, in kilometers. The distance between these points, following the surface of the Earth, in Kilometers is: distance = 6371.01arccos(sin(t1).sin(t2) + e0s(¢1)cos(t2)cos(glg2)) Hint: Use the math module contains a function named radians which converts from degrees to radians, 2.3 Write a Python program that reads a duration from the user as a number of days, hours, minutes, and seconds. Compute and display the total number of seconds represented by this duration. 2.4 Write a program that begins by reading a temperature from the user in de- grees Celsius. Then the program will display the equivalent temperature in degrees Fahrenheit and degrees Kelvin, The calculations needed to convert between different units of temperature can be found on the Internet. 2.5 Write a Python program accepting a wavelength from the user and reports its color. Display an error message if the wavelength entered by the user is outside of the visible spectrum as follows: Color Wavelength Violet 380 to less than 450 Blue 450 to less than 495 Green 495 to less than 570 Yellow 570 to less than 590 Orange 590 to less than 620 Red 620 to 750 2.6 Write a program that displays a temperature conversion table for degrees Celsius and degrees Fahrenheit. The table will include rows for all temper- atures between 0 and 100 degrees Celsius that are multiples of 10 degrees Celsius. Include appropriate headings on your columns. The formula for converting between degrees Celsius and degrees Fahrenheit can be found on the Internet. 2.7 Write a Python program to print alphabet pattern “V” 2.8 Write a Python program to count the number of even and odd numbers from a series of numbers. Example: Sample numbers : 1, 2, 3, 4, 5, 6, 7, 8, 9 Expected Output : Number of even numbers 5 Nurnber of odd numbers : 4 2.9 Write a Python program to find the largest number from a list. Example: Sample List : 15, 26, 30, 40, 55, 36, 27, 81, 19 Expected Output : 81 2.10 Write a Python program to select common items from two lists Example: Sample lists : L1: [15, 26, 90, 40, 95, 96, 27, 81, 19] L2: |16, 28, 31, 40, 56, 36, 27, 80, 29] Expected Output : [40, 36, 27] 2.11 Write a Python program that reads integers from the user and stores them in a list until the user enters 0 and then display (except for the 0) in reverse order, with one value appearing on each line. 2.12 Write a Python program to sum all the items in a dictionary. 2.13 Write a Python program using a dictionary that determines and displays the number of unique characters in a string entered by the user. For example, Hello VKUer! has 10 unique characters while xxx has only one unique character. 2.14 Write a Python program to replace dictionary values with their average 2.15 Write a Python program to check whether an element exists within a tuple 2.16 Write a Python program to reverse a tuple. Jse the function reserve() 26 2.17 Write a Python program to find maximum and the minimum value in a set. Hi : Use the functions max() and min() 2.18 Write a Python program to check if a given set is a superset. of another given set. Hint: Use the funetion issuperset() 2.19 Write a Python program to remove the intersection of a 2nd set from the Ist set. Example: - Original sets: {1, 2, 3, 4, 5} and {4, 5, 6, 7, 8} - Remove the intersection of a 2nd set from the Ist set: snt: {1, 2, 3} and sn2: {4, 5, 6, 7, 8} Hint: Use the function difference _update() or the operator -= 2.20 Write a Python function to multiply all the even numbers in a list. Example: Sample List : 9, 1, 2, -1, 8 Expected Output : -16 2.21 Write a Python function to compute the taxi fare that takes the distance travelled (in kilometers) as its only parameter and returns the total taxi fare as its only result. The caculation of taxi fares includes a base fare of 16,000 dong, plus 8,000 dong for every 1 kilometer travelled.The function will take the distance travelled (in kilometers) as its only parameter and returns the total fare as its only result. A main program is also required to demonstrate the function. 2.22 Write a Python function to read and display last n lines of a text file. 2.23 Write a Python function to count the number of lines in a text file. 2.24 Write a Python program that sums all of the numbers entered by the user while ignoring any input that is not a valid number. The program will display the current sum after each number is entered. It should display an appropriate message after each non-numeric input, and then continue to sum any additional numbers entered by the user. Exit the program when the user enters a blank line. Ensure that the program works correctly for both integers and floating-point numbers. + Use exceptions without using files. 27

You might also like