COMPSCI 107 Computer Science Fundamentals Lecture 03 – Python syntax functions modules
Learning outcomes At the end of this lecture, you should be able to: Use built-in functions Format a string to display output Use functions from the Python API Use import statements to import modules Define and call functions that accept arguments and return values Use keyword arguments for functions COMPSCI 107 - Computer Science Fundamentals
Built-in functions Python provides a wide range of built-in functions, including round(value [, number of decimal places]) max(value, value [, value …]) min(value, value [, value …]) abs(value) float(value) int(value) str(value) type(value) COMPSCI 107 - Computer Science Fundamentals
Strings and string methods Strings are defined in the following ways: 'Single Quotes' "Double Quotes" '''Triple single quotes''' --- this string can span multiple lines Strings have methods that do something with the string data See Python documentation for the full list of methods https://docs.python.org/3/library/stdtypes.html#string-methods String method >>> greeting = 'hello'.capitalize() >>> print(greeting) Hello COMPSCI 107 - Computer Science Fundamentals
https://docs.python.org/3/library/string.html#formatstrings Formatting strings str.format(args) where str contains a replacement field surrounded by {} Can format numbers in a variety of ways >>> name = 'Andrew' >>> greeting = 'Hello, my name is {}'.format(name) >>> print(greeting) Hello, my name is Andrew >>> 'Hello {} {}'.format(first, last) 'Hello Andrew Luxton-Reilly' >>> '{}'.format(math.pi) '3.141592653589793‘ >>> '{:.2f}'.format(math.pi) '3.14' https://docs.python.org/3/library/string.html#formatstrings COMPSCI 107 - Computer Science Fundamentals
Exercise The following example shows how to print out a floating point value as a percentage: Given the following values: Complete the python statement that will print out the marks as a percentage , to 2 decimal places >>> '{:.5%}'.format(math.pi) '314.15927%' >>> total = 35 >>> marks = 13 >>> print( ) COMPSCI 107 - Computer Science Fundamentals
Importing modules Code is stored in modules We want to reuse code as much as possible Build up libraries of code Importing a module allows you to access code in that module Python.org has a list of all the modules and functions provided >>> import math >>> math.pi 3.141592653589793 >>> math.sqrt(4) 2.0 COMPSCI 107 - Computer Science Fundamentals
Exercises Write a program to read the radius of a circle from the user, and print out the circumference of a circle with the input radius. Note: circumference = 2πr COMPSCI 107 - Computer Science Fundamentals
Functions A function is a sequence of instructions designed to perform a task, and is packaged as a unit. Functions have a name Functions accept arguments Functions return values Syntax Indentation rather than braces are used to signify blocks of code Variables defined within the scope of a function are not available outside the function def rectangle_area(width, height): return width * height COMPSCI 107 - Computer Science Fundamentals
Functions without a return value Some functions perform a task that doesn’t evaluate to a value Functions that don’t explicitly return a value will evaluate to None def print_greeting(): print('Hello') print('How are you?') def print_named_greeting(name): print('Hello', name) print('How are you?') >>> x = print_greeting() Hello How are you? >>> print(x) None COMPSCI 107 - Computer Science Fundamentals
Functions with a return value Most functions return a value Use the return keyword def calculate_sum(a, b): return a + b import math def point_inside(centre_x, centre_y, radius, point_x, point_y): EPSILON = 0.00001 dx = abs(centre_x - point_x) dy = abs(centre_y - point_y) hyp = math.sqrt(dx **2 + dy **2) return hyp < radius + EPSILON COMPSCI 107 - Computer Science Fundamentals
Exercises Write a function called triangle_area(base, height) that returns the area of a triangle given the base and the height. height base COMPSCI 107 - Computer Science Fundamentals
Calling functions with keyword arguments Functions are called by passing a value for each parameter Order of the values matches the order of parameters You may use the name of the parameter when you pass the values If you use the name, then you can pass the values in any order def greeting(name, message): print('Hello {}. {}'.format(name, message)) >>> greeting('Andrew', 'Welcome to COMPSCI 107') Hello Andrew. Welcome to COMPSCI 107 >>> greeting(name = 'Andrew', message = 'Welcome to COMPSCI 107') >>> greeting(message = 'Welcome to COMPSCI 107', name = 'Andrew') COMPSCI 107 - Computer Science Fundamentals
print() keyword arguments print('a', 'b', 'c') is the same as print('a', 'b', 'c', sep=' ', end='\n') >>> print('a', 'b', 'c', sep=' ', end='\n') a b c >>> print('a', 'b', 'c', sep='', end='\n') abc >>> print('a', 'b', 'c', sep='---', end='!') a---b---c! COMPSCI 107 - Computer Science Fundamentals
Exercises What is the output when the following program is executed? print('a', end='') print('b', 'c', sep='--') print('d') COMPSCI 107 - Computer Science Fundamentals
Functions with default values Consider the following function: Values are required for all parameters listed in the definition If we provide a default value in the definition, then we don’t need a value for that parameter when we call the function def greeting(name, message): print('Hello {}. {}'.format(name, message)) >>> greeting('Andrew', 'Welcome to COMPSCI 107') Hello Andrew. Welcome to COMPSCI 107 def greeting(name, message='How are you?'): print('Hello {}. {}'.format(name, message)) >>> greeting('Andrew', 'Welcome to COMPSCI 107') Hello Andrew. Welcome to COMPSCI 107 >>> greeting('Andrew') Hello Andrew. How are you? COMPSCI 107 - Computer Science Fundamentals
Summary Code can be more easily reused when it is placed in a function or module Modules may be imported to access the functions stored in them Functions may have parameters Parameters may have default values Functions can be called without passing values to parameters that have default values COMPSCI 107 - Computer Science Fundamentals