Lab 7 Solutions PDF

Title Lab 7 Solutions
Course Introduction to Programming
Institution Dublin City University
Pages 5
File Size 136.8 KB
File Type PDF
Total Downloads 67
Total Views 133

Summary

This is the solution for the seventh lab exercise session by Professor Qun Liu....


Description

Lab 7 1. Sum of Numbers Assume that a file containing a series of integers is named numbers.txt and exists on the computer’s disk. Write a program that reads all of the numbers stored in the file and calculates their total. Solution: def main(): # Declare variables line = '' total = 0.0 number = 0.0 # Open numbers.txt file for reading infile = open('numbers.txt', 'r') for line in infile: number = float(line) total += number # Close file infile.close() # Display the total of the numbers in the file print('Total: ', total)

# Call the main function. main()

2. Exception Handing Modify the program that you wrote for Exercise 1 so it handles the following exceptions: • It should handle any IOError exceptions that are raised when the file is opened and data is read from it. • It should handle any ValueError exceptions that are raised when the items that are read from the file are converted to a number.

Solution: def main(): # Declare local variables total = 0.0 number = 0.0 counter = 0 try: # Open numbers.txt file for reading infile = open('numbers.txt', 'r') for line in infile: counter = counter + 1 number = float(line) total += number # Close file infile.close() # Calculate average average = total / counter # Display the average of the numbers in the file print ('Average:', average) except IOError: print('An error occurred while trying to read the file.') except ValueError: print('Non-numeric data found in the file') except: print('An error occurred') # Call the main function. main()

3. Prime Number A prime number is a number that is only evenly divisible by itself and 1. For example, the number 5 is prime because it can only be evenly divided by 1 and 5. The number 6, however, is not prime because it can be divided evenly by 1, 2, 3, and 6. Write a Boolean function named is_prime which takes an integer as an argument and returns True if the argument is a prime number, or False otherwise. Use the function in a program that prompts the user to enter a number and then displays a message indicating whether the number is prime. Hint: The question is similar to Lab 4 Question 3, but pls re-code it with functions such as is_prime() and main(). Solution: # main function def main(): # Local variable number = 0 # Get number number = int(input('Enter an integer: ')) # display information regarding whether the number is prime if is_prime(number): print ('The number you entered is a prime number.') else: print ('The number you entered is not a prime number.') # The is_prime function receives a number as an argument, # and returns True if number is prime, False otherwise. def is_prime(number): # Local variables half = int(number / 2) status = True for count in range(2, half + 1): if number % count == 0: status = False return status # Call the main function. main()

4. Prime Number List This exercise assumes that you have already written the is_prime function in Question 1 (Prime numbers). Write another program that displays all the prime numbers from 1 to 100. The program should have a loop that calls the is_prime function. Solution: # main function def main(): # local variable totalNumbers = 100 print('number', '\t', 'is prime') print ('------------------------') # For each number, print whether or not it is prime for number in range(1, totalNumbers + 1): # Show if number is prime if is_prime(number): print (number, '\t', 'prime') else: print (number, '\t', 'not prime') # The is_prime function receives a number as an argument, # and returns True if number is prime, False otherwise. def is_prime(number): # Local variables half = int(number / 2) status = True for count in range(2, half + 1): if number % count == 0: status = False return status # Call the main function. main()

5. Writing your own Modules Write a program that asks the computer calculates (add, subtract, multiply and divide) two input numbers and displays the answers. You need to: 1, define a function named asmd in a file named calculation.py. ● Two arguments (input numbers); ● Add, subtract, multiply and divide among these two numbers; ● Return the four calculation results. 2, define the main function in another file named user.py. ● Ask user input two integer numbers; ● Call the function asmd to calculate these two numbers; ● Print the answers. Hint: do it according the example:

Solution:

alculation.py def asmd(number1, number2): add_res = number1+number2 subtract_res = number1-number2 multiply_res = number1*number2 divide_res = float(number1)/number2 return add_res,subtract_res,multiply_res,divide_res

user.py import calculation num1 = int(input("pls type the first number:")) num2 = int(input("pls type the second number:")) add_res,subtract_res,multiply_res,divide_res = calculation.asmd(num1,num2) print (add_res,subtract_res,multiply_res,divide_res)...


Similar Free PDFs