Download presentation
Presentation is loading. Please wait.
Published byCarmella Hood Modified over 9 years ago
1
Functions and Modules CSIS 1595: Fundamentals of Programming and Problem Solving 1
2
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 http://pypi.python.org/pypi
3
Example: Math Module Contains basic math functions – Square root – Trig functions – Logarithms… Can get complete description of any module using help(“modulename”)
4
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)
5
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
6
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 1.5707963267948966 – Evaluates to math.cos( 1.5707963267948966 ) Example: input value and convert to number in single statement x = float(input(“Enter a number: “))
7
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
8
Constants Numbers (and other things) with fixed value Often built into modules – Syntax: modulename.constant Examples in math module: – math.pi evaluates to 3.14159… – math.e area = math.pi * radius ** 2
9
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)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.