Functions and Modules CSIS 1595: Fundamentals of Programming and Problem Solving 1
Modules Python small language with few command – True of most modern languages (efficiency) Can import additional capabilities as modules Syntax: import modulename Can get list of all modules with help(“modules”) – Just those included with Python download – Many others available at
Example: Math Module Contains basic math functions – Square root – Trig functions – Logarithms… Can get complete description of any module using help(“modulename”)
Functions and Modules Modules contain functions Syntax: modulename.functionname(…) Example: square root sqrt function x = math.sqrt(2) a = 3 b = 5 * math.sqrt(a + 1)
Evaluating Expressions with Functions Functions take arguments as input – Values inside () after function name Functions (may) return a value – What function evaluates to in expression Steps in evaluating expression with functions on RHS: 1.Evaluate expressions that are function arguments 2.Evaluate function using those arguments 3.Use return value in place of function in expression 4.Evaluate rest of expression
Evaluating Nested Functions Functions can use other functions as arguments – Evaluate inner function first – Use return value in argument of outer function Example: x = math.cos(math.radians(45)) – math.radians(45) returns – Evaluates to math.cos( ) Example: input value and convert to number in single statement x = float(input(“Enter a number: “))
Functions with List of Arguments Example: print function Example: math.pow(value1, value2) – Same as value1 ** value2 Note that order of parameters matters – math.pow(2, 3) 8 – math.pow(3, 2) 9
Constants Numbers (and other things) with fixed value Often built into modules – Syntax: modulename.constant Examples in math module: – math.pi evaluates to … – math.e area = math.pi * radius ** 2
Random Numbers Many functions in random module – random.random() Returns random float between 0 and 1 – random.randint(lower, upper) Returns random int between lower and upper (inclusive) Example: dice1 = random.randint(1, 6) dice2 = random.randint(1, 6) print(“You rolled a”, dice1, “and a”, dice2)