✓ Function – It is used to perform sequence of statements.
✓ Type Conversion Functions – Python’s built-in functions are used to convert values from one type to another.
>>> int('32') 32 >>> int('Hello') ValueError: invalid literal for int(): Hello >>> int(3.99999) 3 >>> int(-2.3) -2 >>> float(32) 32.0 >>> float('3.14159') 3.14159 >>> str(32) '32' >>> str(3.14159) '3.14159'
✓ Math Functions – Python’s math module is used to perform most of the familiar mathematical functions.
>>> import math >>> print math <module 'math' (built-in)> >>> ratio = signal_power / noise_power >>> decibels = 10 * math.log10(ratio) >>> radians = 0.7 >>> height = math.sin(radians) #Composition x = math.sin(degrees / 360.0 * 2 * math.pi) x = math.exp(math.log(x+1))
✓ Creating new functions
def print_lyrics(): print "I'm a lumberjack, and I'm okay." print "I sleep all night and I work all day." def repeat_lyrics(): print_lyrics() print_lyrics() repeat_lyrics()
✓ Functions with parameters and arguments
def print_twice(bruce): print bruce print bruce >>> print_twice('Spam') Spam Spam >>> print_twice(17) 17 17 >>> print_twice(math.pi) 3.14159265359 3.14159265359
✓ Value returning functions and void functions
# Value returning fucntions x = math.cos(radians) golden = (math.sqrt(5) + 1) / 2 #Void functions >>> result = print_twice('Bing') Bing Bing
✶ Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place.
✶ Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole.
✶ Well-designed functions are often useful for many programs. Once you write and
debug one, you can reuse it.
✓ Importing functions
#If you import math, you get a module object named math. >>> import math >>> print math <module 'math' (built-in)> >>> print math.pi 3.14159265359 >>> print pi Traceback (most recent call last): File "", line 1, in NameError: name 'pi' is not defined # Importing objects from module >>> from math import pi >>> print pi 3.14159265359 #you can use the star operator to import everything from the module >>> from math import * >>> cos(pi) -1.0