Download presentation
Presentation is loading. Please wait.
1
COMPSCI 107 Computer Science Fundamentals
Lecture 03 – Python syntax functions modules
2
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 Computer Science Fundamentals
3
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 Computer Science Fundamentals
4
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 String method >>> greeting = 'hello'.capitalize() >>> print(greeting) Hello COMPSCI Computer Science Fundamentals
5
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) ' ‘ >>> '{:.2f}'.format(math.pi) '3.14' COMPSCI Computer Science Fundamentals
6
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) ' %' >>> total = 35 >>> marks = 13 >>> print( ) COMPSCI Computer Science Fundamentals
7
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 >>> math.sqrt(4) 2.0 COMPSCI Computer Science Fundamentals
8
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 Computer Science Fundamentals
9
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 Computer Science Fundamentals
10
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 Computer Science Fundamentals
11
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 = dx = abs(centre_x - point_x) dy = abs(centre_y - point_y) hyp = math.sqrt(dx **2 + dy **2) return hyp < radius + EPSILON COMPSCI Computer Science Fundamentals
12
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 Computer Science Fundamentals
13
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 Computer Science Fundamentals
14
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 Computer Science Fundamentals
15
Exercises What is the output when the following program is executed?
print('a', end='') print('b', 'c', sep='--') print('d') COMPSCI Computer Science Fundamentals
16
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 Computer Science Fundamentals
17
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 Computer Science Fundamentals
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.