Sample Code
def hello(name):
answer = "Hello " + name
return answer
print(hello("George"))
print(hello("Gill"))
def isChild(age):
if age < 18:
return "Child"
else:
return "Adult"
print(isChild(35))
def AreaRect(length, width):
return length*width
l = int(input("Enter the length"))
w = int(input ("Enter the width"))
print(AreaRect(l, w))
PI = 3.1415
def main():
radius = 4
print("The area of a circle radius ", radius, " is ", Area(radius))
def Area(r):
return PI*r*r
main()
Exercises
- Write a function that accepts a string and returns “Pleased to meet you, ” + string
- Write a function that accepts a number and returns “Child” if the number is <18 and “Adult” otherwise
- Write a function that accepts a number and returns “Grade A” if the number is >20, “Grade B” if the number is >15, “Grade C” if the number is >10 and “Fail” otherwise.
- Write a function that accepts two numbers and returns the average of the numbers
- Write a function that accepts three integers and returns the average of the numbers.
- Write a function that accepts the length and width of a rectangle and returns the perimeter of the rectangle
- Write a function that accepts the base and height of a triangle and returns the area of the triangle
- Write a function that accepts a list and returns the sum of the list
Extension
- Write a function that returns the hypotenuse of a triangle when the other two sides are int a and int b. (Remember: hypotenuse squared equals a squared plus b squared)
- The scalar product of u=(u1,u2,u3) and v=(v1,v2,v3) is defined to be u1v1+u2v2+u3v3. Write a function that accepts two int tuples as parameters and returns an int representing the scalar product of those two tuples
- If A = (a1,a2, …an) and B = (b1,b2, …bn) then the vector sum of the two tuples A + B = (a1+b1, a2+b2, … , an+bn). Write a function that accepts two tuples as parameters and returns an array representing the vector sum of those two tuples
- The Euclidean distance between two points A = (a1,a2, …an) and B = (b1,b2, …bn) is defined as sqrt((a1-b1)2 + (a2-b2)2 +… + (an-bn)2). Write a function that accepts two int tuples representing A and B as parameters and returns a double representing the Euclidean distance between them.
Like this:
Like Loading...
Related
Published by Tony Ballantyne
Writer and Tech blogger
View all posts by Tony Ballantyne