COMPSCI 107 Computer Science Fundamentals

Slides:



Advertisements
Similar presentations
Lecture 07 – Iterating through a list of numbers.
Advertisements

Lecture 04 – Classes.  Python has a number of classes built-in  lists, dictionaries, sets, int, float, boolean, strings  We can define our own classes.
Lecture 03 – Sequences of data.  At the end of this lecture, students should be able to:  Define and use functions  Import functions from modules 
Lecture 05 – Classes.  A class provides the definition for the type of an object  Classes can store information in variables  Classes can provide methods.
Functions and abstraction Michael Ernst UW CSE 190p Summer 2012.
Classes 2 COMPSCI 105 S Principles of Computer Science.
Functions.
COMPSCI 101 Principles of Programming
Munster Programming Training
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
Introduction. 2COMPSCI Computer Science Fundamentals.
Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.
COMPSCI 101 Principles of Programming Lecture 25 – Nested loops, passing mutable objects as parameters.
Functions, Procedures, and Abstraction Dr. José M. Reyes Álamo.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
Introduction to Computing Using Python for loop / def- ining a new function  Execution control structures ( if, for, function call)  def -ining a new.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Python Functions : chapter 3
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
Classes COMPSCI 105 SS 2015 Principles of Computer Science.
Lecture 09 – Classes.  At the end of this lecture, students should be able to:  Define a new class  Store state information about instances of the.
Variables, Types, Expressions Intro2CS – week 1b 1.
COSC 1223 Computer Science Concepts I Joe Bryan. What is a function? Like a mini-program that performs a specific task Two types: Built-in functions Functions.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Chapter 6 Functions The Tic-Tac-Toe Game. Chapter Content In this chapter you will learn to do the following: 0 Write your own functions 0 Accept values.
Information and Computer Sciences University of Hawaii, Manoa
Chapter 9: Value-Returning Functions
COMPSCI 107 Computer Science Fundamentals
Topics Designing a Program Input, Processing, and Output
Topics Introduction to Functions Defining and Calling a Void Function
Introduction to Python
Topic: Python’s building blocks -> Statements
COMPSCI 107 Computer Science Fundamentals
Functions Chapter 4 Python for Everybody
Variables, Expressions, and IO
Fundamentals of Programming I Managing the Namespace
Functions CIS 40 – Introduction to Programming in Python
Functions.
OUTPUT STATEMENTS GC 201.
Imperative Programming
Line Continuation, Output Formatting, and Decision Structures
Functions, Procedures, and Abstraction
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Topics Designing a Program Input, Processing, and Output
5. Functions Rocky K. C. Chang 30 October 2018
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Functions Jay Summet.
Introduction to Value-Returning Functions: Generating Random Numbers
G. Pullaiah College of Engineering and Technology
Topics Designing a Program Input, Processing, and Output
15-110: Principles of Computing
Topics Designing a Program Input, Processing, and Output
Beginning Python Programming
COMPUTER PROGRAMMING SKILLS
Python Functions.
What is a Function? Takes one or more arguments, or perhaps none at all Performs an operation Returns one or more values, or perhaps none at all Similar.
CISC101 Reminders Assignment 3 due today.
More Basics of Python Common types of data we will work with
def-ining a function A function as an execution control structure
Functions, Procedures, and Abstraction
 A function is a named sequence of statement(s) that performs a computation. It contains  line of code(s) that are executed sequentially from top.
Imperative Programming
Functions Jay Summet.
© Sangeeta M Chauhan, Gwalior
Using Modules.
Introduction to Python
Presentation transcript:

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