Assesment Solutions

Find the volume and surface area of a cylinder (height=2, radius=3)by defining the cylinder class.

class cylinder:

    pi = 3.14

    def __init__(self, height, radius):
        self.radius = radius
        self.height = height

    def volume(self):
        volume = self.height*self.pi*self.radius**2
        print('Volume of the cylinder is {}'. format(volume))

    def surface_area(self):
        area = (2*self.pi*self.radius**2) + (2*self.pi*self.radius*self.height)
        print('Surface area of the cylinder is {}'. format(area))
c = cylinder(2,3)
c.volume()
Volume of the cylinder is 56.52
c.surface_area()
Surface area of the cylinder is 94.2

Write a function that asks for an integer and prints the square of it. Use a while loop with a try, except, else block to account for incorrect inputs.

def ask():
    while True:
        try:
            num1 = int(input('Please enter a number: '))
            #result = num1**2
        except:
            print('An error occurred! Please try again!')
            continue
        else:
            result = num1**2
            print(f'Thank you. Your number squared is: {result}')
            break
ask()
Please enter a number: d
An error occurred! Please try again!
Please enter a number: 2
Thank you. Your number squared is: 4

Create a generator that generates the squares of numbers up to some number N.

def gensquares(N):
    for i in range(N):
        yield i**2
g = gensquares(10)
print(next(g))
0
print(next(g))
1
print(next(g))
4

Create a generator that yields "n" random numbers between a low and high number (that are inputs).

import random

def rand_num(low,high,n):

    for i in range(n):
        yield random.randint(low, high)
list(rand_num(1,10,12))
[6, 3, 7, 7, 1, 1, 2, 7, 1, 6, 3, 4]

Write a Python program that matches a string that has an a followed by one or more b's.

import re
def text_match(text):
        patterns = 'ab+'
        if re.search(patterns,  text):
            return ('Found a match!')
        else:
            return ('Not matched!')
print(text_match("ab"))
Found a match!
print(text_match("ac"))
Not matched!

Write a Python program to get the current time.

import datetime
print(datetime.datetime.now().time())
17:31:04.520057
print(datetime.datetime.today())
2020-07-11 17:32:04.747523

Write a Python program to determine whether a given year is a leap year

    def leap_year(y):
        if y % 400 == 0:
            return True
        if y % 100 == 0:
            return False
        if y % 4 == 0:
            return True
        else:
            return False