FinalAssesment
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()
c.surface_area()
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()
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))
print(next(g))
print(next(g))
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))
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"))
print(text_match("ac"))
Write a Python program to get the current time.
import datetime
print(datetime.datetime.now().time())
print(datetime.datetime.today())
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