Computer Science 1 CSci 1100 Lecture 3 Python Functions



Similar documents
Introduction to Python

Basic Math for the Small Public Water Systems Operator

Solids. Objective A: Volume of a Solids

Introduction to Python

Informatica e Sistemi in Tempo Reale

Perimeter, Area, and Volume

Surface Area Quick Review: CH 5

CS 100 Introduction to Computer Science Lab 1 - Playing with Python Due September 21/23, 11:55 PM

Software Development. Topic 1 The Software Development Process

Calculating Area, Perimeter and Volume

Area of a triangle: The area of a triangle can be found with the following formula: in

Math 0306 Final Exam Review

CSCE 110 Programming I Basics of Python: Variables, Expressions, and Input/Output

Almost all spreadsheet programs are based on a simple concept: the malleable matrix.

Programming a mathematical formula. INF1100 Lectures, Chapter 1: Computing with Formulas. How to write and run the program.

Using Excel to find Perimeter, Area & Volume

Mathematics Placement Examination (MPE)

Python Programming: An Introduction to Computer Science

Decision Logic: if, if else, switch, Boolean conditions and variables

Revision Notes Adult Numeracy Level 2

VOLUME of Rectangular Prisms Volume is the measure of occupied by a solid region.

FEEG Applied Programming 5 - Tutorial Session

Introduction to Python for Text Analysis

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

The GED math test gives you a page of math formulas that

Chapter 2 Writing Simple Programs

YOU MUST BE ABLE TO DO THE FOLLOWING PROBLEMS WITHOUT A CALCULATOR!

Florida Algebra 1 End-of-Course Assessment Item Bank, Polk County School District

12-1 Representations of Three-Dimensional Figures

Chapter 3. Input and output. 3.1 The System class

MATHEMATICS FOR ENGINEERING BASIC ALGEBRA

MAT 2170: Laboratory 3

CHAPTER 8, GEOMETRY. 4. A circular cylinder has a circumference of 33 in. Use 22 as the approximate value of π and find the radius of this cylinder.

Area & Volume. 1. Surface Area to Volume Ratio

CALCULATING THE AREA OF A FLOWER BED AND CALCULATING NUMBER OF PLANTS NEEDED

Geometry - Calculating Area and Perimeter

Algebra Geometry Glossary. 90 angle

GAP CLOSING. Volume and Surface Area. Intermediate / Senior Student Book

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Show that when a circle is inscribed inside a square the diameter of the circle is the same length as the side of the square.

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Invitation to Ezhil : A Tamil Programming Language for Early Computer-Science Education 07/10/13

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

CSC 120: Computer Science for the Sciences (R section)

G r a d e 1 0 I n t r o d u c t i o n t o A p p l i e d a n d P r e - C a l c u l u s M a t h e m a t i c s ( 2 0 S ) Final Practice Exam

Chapter 8 Geometry We will discuss following concepts in this chapter.

What's New in ADP Reporting?

Area of a triangle: The area of a triangle can be found with the following formula: You can see why this works with the following diagrams:

General Software Development Standards and Guidelines Version 3.5

Course Title: Software Development

Geometry Notes VOLUME AND SURFACE AREA

Microsoft Windows PowerShell v2 For Administrators

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Pizza! Pizza! Assessment

Math 1B, lecture 5: area and volume

CSC 221: Computer Programming I. Fall 2011

Java CPD (I) Frans Coenen Department of Computer Science

FCAT FLORIDA COMPREHENSIVE ASSESSMENT TEST. Mathematics Reference Sheets. Copyright Statement for this Assessment and Evaluation Services Publication

Name: Date: Period: PIZZA! PIZZA! Area of Circles and Squares Circumference and Perimeters Volume of Cylinders and Rectangular Prisms Comparing Cost

CSCI 1100 Computer Science 1 Homework 1 Calculations and Functions

Assignment 2: Option Pricing and the Black-Scholes formula The University of British Columbia Science One CS Instructor: Michael Gelbart

PYTHON Basics

Writing Simple Programs

Python Programming: An Introduction to Computer Science

2013 Getting Started Guide

Python Lists and Loops

ModuMath Basic Math Basic Math Naming Whole Numbers Basic Math The Number Line Basic Math Addition of Whole Numbers, Part I

LAB4 Making Classes and Objects

Creating and Using Databases with Microsoft Access

CS101 Lecture 24: Thinking in Python: Input and Output Variables and Arithmetic. Aaron Stevens 28 March Overview/Questions

Exercise 4 Learning Python language fundamentals

ECDL / ICDL Spreadsheets Syllabus Version 5.0

CGN Computer Methods

2/1/2010. Background Why Python? Getting Our Feet Wet Comparing Python to Java Resources (Including a free textbook!) Hathaway Brown School

Area of Parallelograms, Triangles, and Trapezoids (pages )

Keystone National High School Placement Exam Math Level 1. Find the seventh term in the following sequence: 2, 6, 18, 54

Computer Programming I & II*

Double Integrals in Polar Coordinates

Grade 6 FCAT 2.0 Mathematics Sample Questions

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

16 Circles and Cylinders

Welcome to Introduction to programming in Python

Math. So we would say that the volume of this cube is: cubic units.

1. The volume of the object below is 186 cm 3. Calculate the Length of x. (a) 3.1 cm (b) 2.5 cm (c) 1.75 cm (d) 1.25 cm

HVAC FORMULAS. TON OF REFRIGERATION - The amount of heat required to melt a ton (2000 lbs.) of ice at 32 F. 288,000 BTU/24 hr. 12,000 BTU/hr.

Relational Database: Additional Operations on Relations; SQL

Microsoft Word Quick Reference Guide. Union Institute & University

Programming Languages

ECE 341 Coding Standard

Exercise 0. Although Python(x,y) comes already with a great variety of scientic Python packages, we might have to install additional dependencies:

SA B 1 p where is the slant height of the pyramid. V 1 3 Bh. 3D Solids Pyramids and Cones. Surface Area and Volume of a Pyramid

SURFACE AREA AND VOLUME

Profiling, debugging and testing with Python. Jonathan Bollback, Georg Rieckh and Jose Guzman

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Think About This Situation

Intro to scientific programming (with Python) Pietro Berkes, Brandeis University

Getting Started in Tinkercad

Basic tutorial for Dreamweaver CS5

Transcription:

Reading Computer Science 1 CSci 1100 Lecture 3 Python Functions Most of this is covered late Chapter 2 in Practical Programming and Chapter 3 of Think Python. Chapter 6 of Think Python goes into more detail, but we are not quite ready for that yet. Back to Area and Volume Calculation Recall our program to compute the surface area and volume of a cylinder: >>> >>> radius = 2 >>> height = 10 >>> base_area = pi * radius ** 2 >>> volume = base_area * height >>> surface_area = 2 * base_area + 2 * pi * radius * height >>> print "volume is", volume, ", surface area is", surface_area volume is 125.6636, surface area is 150.79632 If we want to run all or part of this again, on different values, we either have to edit the program and rerun it, or we have to type the statements all over again. Instead, we will gather the code into one or more Python functions that we can run repeatedly. The purpose of today s class is to introduce the basics of writing and running Python functions. A Function to Compute the Area of a Circle In mathematics, you might write a function to calculate the area of a circle as a(r) = πr 2 In Python, when typing directly into the interpreter, we write >>> def area_circle(radius):...... return pi * radius ** 2 Then we can run this using >>> area_circle(1) >>> area_circle(2) >>> area_circle(75.1) Note that by using examples with small values for the radius we can easily check that our function is correct. Important syntax includes Use of the keyword def and the : to indicate the start of the function Indentation for the lines after the def line Blank line at the end of the function

The... are produced by the Python interpreter, just like the >>> are. What does Python do as we type? 1. Reads the keyword def and notes that a function is being defined 2. Reads the rest of the function definition, checking its syntax 3. Notes the end of the definition when the blank line is reached. 4. Sees the function call >>> area_circle(1) at what s known as the top level or main level of execution (indicated by the presence of >>>), and Jumps back up to the function Assigns 1 to radius Runs the code inside the function Returns the result of the calculation back to the top level and outputs the returned result 5. Repeats the process of running the function at the line >>> area_circle(2) this time with radius assigned the value 2 6. Repeats the process again at the line >>> area_circle(75.1) To reiterate, the flow of control of Python here involves Reading the function definition without executing Seeing a call to the function, jumping up to the start of the function and executing Returning back to the place in the program that called the function and continuing. Arguments, Parameters and Local Variables Arguments are the values 1, 2 and 75.1 in our above examples. These are each passed to the parameter called radius named in the function header. This parameter is used just like a variable in the function. The variable pi is a local variable to the function. Neither pi nor radius exists at the top / main level. At this level, they are undefined variables. Try it out. Exercise Write a function to convert the Celsius temperature to a Fahrenheit temperature. Write code to use the function. What are the arguments, parameters and local variables? 2

Functions with Multiple Arguments / Parameters For our volume calculation, we write a function involving two parameters, called with two arguments: >>> def volume(radius, height):...... return pi * radius ** 2 * height... >>> print "volume of cylinder with radius", 1, "and height 2 is", volume(1,2) >>> print "volume of cylinder with radius", 2, "and height 1 is", volume(2,1) Python determines which argument goes to which parameter based on the order of the arguments, the first going to radius and the second going to height. In this example, we have provided clearer, more extensive output. Python and Program Files Ways to run Python code include: Typing directly into the Python interpreter. This is what we do at the bottom of the Wing IDE. The >>> and... symbols are generated by the interpreter when we are typing in the program directly. Typing our code into a file (which we will call volume.py) and then either Opening the interpreter and running the code Running the Python code from a command shell The latter is in fact the most common way of running Python programs in practice. We will demonstrate all three in class. Note that providing more information in our print statement makes the output of the program from the command-line more self-explanatory. Functions That Call Functions Let s make use of our area of circle function to compute the surface area of the cylinder. Here is the Python code, in file surface_area.py: def area_cylinder(radius,height): circle_area = area_circle(radius) height_area = 2 * radius * pi * height return 2*circle_area + height_area def area_circle(radius): return pi * radius ** 2 print The area of a circle of radius 1 is, area_circle(1) r = 2 height = 10 print The surface area of a cylinder with radius, r print and height, height, is, area_cylinder(r,height) Now we ve defined two functions, one of which calls the other. 3

Flow of control proceeds in two different ways here: 1. Starting at the first print at the top level, into area_circle and back. 2. At the second print (a) into area_cylinder, (b) into area_circle, (c) back to area_cylinder, and (d) back to the top level. The Python interpreter keeps track of where it is working and where to return when it is done with a function, even if it is back into another function. Exercise Write a function to compute the area of a rectangle. Write a second function that takes the length, width and height of a rectangular solid and computes its surface area. Gathering Our Example Into One Big Function We can gather our code in one complete set of functions, writing them into a file called area_volume.py: def area_circle(radius): return pi * radius ** 2 def volume_cylinder(radius,height): area = area_circle(radius) return area * height def area_cylinder(radius,height): circle_area = area_circle(radius) height_area = 2 * radius * pi * height return 2*circle_area + height_area def area_and_volume(radius, height): print "For a cylinder with radius", radius, "and height", height print "The surface area is", area_cylinder(radius,height) print "The volume is", volume_cylinder(radius,height) Now we have functionality that we can use to generate clear, complete output for many different values of the radius of a circle and the base radius and height of a cylinder. Thinking About What You See Why is it NOT a mistake to use the same name, for example radius, in different functions (and sometimes at the top level). Let s Make Some Mistakes In order to check our understanding, we will play around with the code and make some mistakes on purpose Removing pi 4

Changing the name of a function Switching the order of the parameters in a function call Making an error in our calculation Why Functions? We write code that is Easier to think about and write Easier to test: we can check the correctness of area_circle before we test area_cylinder. Clearer for someone else to read Reusable in other programs Together these define the notion of encapsulation, another important idea in computer science! Python s Built-In Functions A few examples, some of which we have already seen abs pow int float round max min Let s play around to see what they do! Summary Functions for encapsulation and reuse Function syntax Arguments, parameters and local variables Flow of control, including functions that call other functions Built-in functions 5