110 likes | 136 Views
Learn about pre-defined, random, and user-defined mathematical functions in Python. Explore examples and exercises to practice using these functions.
E N D
More Pre-defined mathematic function in Python • argument: may be integer (int) or real (float) • result: real (float) • import math: includes functions and values of π y e • help(math): show list of all mathematic functions
Other pre-defined functions Examples >>> abs(-1) 1 >>> max(3,4,2) 4 >>> min(3,4,2) 2 >>> >>> max(2,3.5) 3.5 >>> min(2,3.5) 2 >>> min(2,2) 2
Functions for generating random numbers >>> import random >>> random.random() 0.3504750773904878 >>> random.randint(1,6) #throw a dice 6 >>> random.randint(0,1) #throw a coin 1
More Pre-defined mathematic function in Python # highest and lowest of 3 random integer # numbers between 1 y 100 import random a=random.randint(1,100) b=random.randint(1,100) c=random.randint(1,100) print “highest=”,max(a,b,c) print “lowest=”,min(a,b,c)
Functions defined by the programmer #function for computing the perimeter of a triangle def perimeter(x,y,z): return x+y+z # function for computing the area of a triangle import math #include mathematic functions def area(x,y,z): s=perimeter(x,y,z)/2.0 #semi-perimeter return math.sqrt(s*(s-x)*(s-y)*(s-z)) Note. A function can call another function
Functions defined by the programmer: “user” program print “perimeter and área of a triangle with sides a,b,c” #get sides a=input(“a?”) b=input(“b?”) c=input(“c?”) #computer and show perimeter and area print “perímeter=”, perimeter(a,b,c) print “area=“, area(a,b,c)
Functions defined by the programmer: rules Syntax def name(parameters): instructions (zero or more) return expression ¿parameters? name, ... (zero or more) Semantic 1º copies (assigns) calling arguments to the function parameters 2º performs instructions 3º computes value of the returning expression 4º returns the expression’s value at calling place Note. Parameters and variables dissapear after the function is performed. Ex. Variables x,y,z and s are not more valid after function area returns
Exercise • Write a function which receives a radius and returns the perimeter of a circle • Write a function which receives a radius and returns the área of a circle • Write a program which gets a side of a square and uses the previous functions to compute the are and perimeter of the following ring: Dialog: Side of the square ? __ Area=___ Perimeter = ___