Introduction to Programming

Similar documents
Introduction to Programming

Introduction to Programming

Introduction to Programming

Introduction to Programming

Introduction to Programming

Introduction to Programming

Introduction to Programming

Software and Programming 1

Software and Programming 1

Previously. Iteration. Date and time structures. Modularisation.

Fundamentals: Expressions and Assignment

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Introduction to Programming

Semester 2, 2018: Lab 1

Using IDLE for

Chapter Five: Functions

Programming for Engineers in Python. Recitation 1

Previously. Iteration. Date and time structures. Modularisation.

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

All programs can be represented in terms of sequence, selection and iteration.

Python for loops. Girls Programming Network School of Information Technologies University of Sydney. Mini-lecture 7

Programming for Engineers in Python. Autumn

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

CS 105 Lab As a review of what we did last week a. What are two ways in which the Python shell is useful to us?

Software and Programming 1

Introduction to: Computers & Programming: Review prior to 1 st Midterm

ENGR/CS 101 CS Session Lecture 12

Software and Programming 1

Introduction to Python

Control Flow: Loop Statements

Unit 7: Algorithms and Python CS 101, Fall 2018

Introduction to Computers. Laboratory Manual. Experiment #3. Elementary Programming, II

Basic Syntax - First Program 1

Computational Mathematics/Information Technology. Worksheet 2 Iteration and Excel

Scientific Computing: Lecture 1

Top bar items. Current folder should be shown. Command Window This has the the prompt >>

Interactive Mode Python Pylab

Part III Appendices 165

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

CMSC 201 Spring 2018

Introduction to Microsoft Excel

Individual research task. You should all have completed the research task set last week. Please make sure you hand it in today.

Molecular Statistics Exercise 1. As was shown to you this morning, the interactive python shell can add, subtract, multiply and divide numbers.

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

A Walkthrough of the Learning Aids

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Course Outline - COMP150. Lectures and Labs

Introduction to Python - Part I CNV Lab

Python Games. Session 1 By Declan Fox

Setup Mount the //geobase/geo4315 server and add a new Lab2 folder in your user folder.

Introduction to Software Development (ISD) Week 3

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Keeping Records: The American Pastime

Introduction Microsoft Word CMPE 101 Fundamentals of Computer Engineering EXPERIMENT - 1

Flow Control: Branches and loops

Com S 127x - Lab 6 1. READING FLOWCHARTS WITH CONDITIONAL ACTIONS!

CSI33 Data Structures

CS1110 Lab 6 (Mar 17-18, 2015)

Level 3 Computing Year 2 Lecturer: Phil Smith

CS Fall Homework 11 p. 1. CS Homework 11

CIS 110: Introduction to Computer Programming

LOOPS. Repetition using the while statement

Introduction to Programming in Turing. Input, Output, and Variables

Chapter 2 Input, Processing and Output. Hong Sun COSC 1436 Spring 2017 Jan 30, 2017

Announcements for This Lecture

Introduction to: Computers & Programming Defining Identifiers: Objects with Names

Python Problems MTH 151. Texas A&M University. November 8, 2017

CpSc 1111 Lab 9 2-D Arrays

Lab 2: Modules This lab accompanies Chapter 3 of Starting Out with Programming Logic & Design.

Objectives. Structure. Munster Programming Training

Week One: Introduction A SHORT INTRODUCTION TO HARDWARE, SOFTWARE, AND ALGORITHM DEVELOPMENT

Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department

ITE 119 Information Literacy

CMSC 201 Computer Science I for Majors

CSE 101 Introduction to Computers Development / Tutorial / Lab Environment Setup

Functions Structure and Parameters behind the scenes with diagrams!

Problem Solving for Intro to Computer Science

CMSC 201 Spring 2019 Lab 06 Lists

DEPARTMENT OF ELECTRICAL AND ELECTRONIC ENGINEERING PROGRAMMING TECHNIQUES I EE271

RETURN X return X Returning a value from within a function: computes the value of variable exits the function and returns the value of the variable

Babu Madhav Institute of Information Technology, UTU 2015

ITE 115 Introduction to Computer Applications

Exercise 2: Automata Theory

UW Department of Chemistry Lab Lectures Online

Lecture 4. Defining Functions

Outlook 2007 Web Access User Guide

RETURN X return X Returning a value from within a function: computes the value of variable exits the function and returns the value of the variable

The while Loop 4/6/16 4

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

Introduction to JES and Programming. Installation

Python Instruction Booklet v7.2

Senthil Kumaran S

Spring CS Homework 3 p. 1. CS Homework 3

Python Unit

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

4.2 Function definitions the basics

MICROSOFT WORD XP INTERMEDIATE

How-To Guides. - Changing the Default Confirmation Message for Your Event. - Cancelling Registrations and Issuing Refunds on Certain

Transcription:

Introduction to Programming Python Lab 9: Functions PythonLab9 lecture slides.ppt 27 November 2018 Ping Brennan (p.brennan@bbk.ac.uk) 1

Getting Started Create a new folder in your disk space with the name PythonLab9 Launch the Python Integrated Development Environment (IDLE) - begin with the Start icon in the lower left corner of the screen. If you are in a DCSIS laboratory, search using the keyword Python and click on IDLE (Python 3.6 64-bit) A window with the title Python 3.6.2 Shell should appear. This window is the Shell. 2

Getting Started (2) If you are in the ITS laboratory MAL 109, select the options in the order shown: Start -> All Programs -> Departmental Software -> Computer Science -> Python 3.4 -> IDLE (Python 3.4 GUI 64 bit) A window with the title Python 3.4.4rc1 Shell should appear. This window is the Shell. If the window does not appear, click on Start and then in the box Search programs and files write IDLE. A list will appear. Click on IDLE(Python 3.4 GUI-64 bit). A window with the title Python 3.4.4rc1 should appear. This window is the Shell. In the Shell click on File. A drop down menu will appear. Click on New File. A window with the title Python 3.4.1: Untitled (DCSIS) or Untitled (ITS) should appear. This window is the Editor. 3

Getting Started (3) In the Editor, click on File, and then in the drop down menu click on Save As. A window showing a list of folders should appear. To search any folder on the list, double click on the folder. Find the folder PythonLab9 and double click on it. In the box File name at the bottom of the window 1. Type CompoundInterest.py 2. Then click on the button Save in the lower right corner of the window. The title of the Editor should change to show the location of the file CompoundInterest.py. 4

Objectives of the exercises set Function header Create your own user-defined functions in your program. Function body, executed when the function is called. The statements in the body should be indented to the same level. When defining a function, you provide a name for the function and a parameter variable for each argument. For example, the definition of the function cubevolume is shown below. Name of function def cubevolume( sidelength ) : volume = sidelength ** 3 return volume result = cubevolume(2) Name of parameter variable Put a colon here. return statement exits the function and returns the result (that is, the value of volume). After the definition of cubevolume, call the function with an argument of 2 to calculate the volume, and then store the returned value 8 in the variable result. 5

Execution flow of a function call to cubevolume 6

Objectives of the exercises set (2) Use a for statement to implement count-controlled loops that iterate over a range of integer values. For example, The start value for i in range( 1, 5, 2 ): print(i) #loop body The ending value is never included in the sequence. The third argument is the step value. Working of the loop: value of i Output using print(i) 1 1 3 3 Recall The range function generates a sequence of integers over which the loop iterates. The variable i is set, at the beginning of each iteration, to the next integer in the sequence generated by the range function. 7

Objectives of the exercises set (3) Use the string format operator % and sensible format specifiers to specify how values should be formatted in the output. For example, print("quantity: %d Cost: %6.2f" % (quantity, cost)) Format specifiers Recall: The format string can contain one or more format specifiers and literal characters. Use the letter d for an integer value, and the letter f for a floating-point value. Recall: The values/variables to be formatted are defined inside the brackets. Each value replaces one of the format specifiers in the resulting string. 8

Program CompoundInterest.py: function balance Question 2: Problem statement Write a function with the name balance and with the following three arguments: initialbalance, rate and numberyears. The function balance returns the balance in an account given the initial balance, the number of years that have elapsed and the interest rate. It is assumed that the interest is compounded. Recall that the balance in the account is given by the formula initialbalance*((1+rate/100)**numberyears) Provide a comment to explain the purpose of the function balance. Also include in your comment the types of the parameter values, the type of the returned value, your name and the date. Save the function balance in the file CompoundInterest.py. 9

Program CompoundInterest.py: function balance (2) Function body, executed when function is called. The print statement is outside the function definition. Problem solving - Convert the pseudocode below into a sequence of Python statements in your program. 1. Define a function named balance as shown below: def balance(initalbalance, rate, numberyears): 2. Create an assignment statement to calculate the final balance using the formula below, and store the result in a variable named finalbalance. Indent the statement. initialbalance*((1+rate/100)**numberyears) 3. Add a return statement to return the result of the function, namely finalbalance, in the function body. The return and the assignment statement in step 2 have the same indentation. 4. Add a print statement to call the function balance, for example print( balance(100, 6, 2) ) Align the function header def and the print statement to the same level of indentation. 10

Program CompoundInterest.py: function balance (3) Save the function balance in the file CompoundInterest.py, and then run the program to test it. 11

Program CompoundInterest.py: function balance (4) Note: You should define the function balance before you call it later in the program. Inputs to the function balance After creating the definition of the function balance, call balance with the following arguments: balance(100, 6, 2) Computation in the function balance Initializing function parameter variables initialbalance is rate is 6 numberyears is Function body: finalbalance = 2 initialbalance*((1+rate/100) **numberyears) return finalbalance 100 Result returned by the function Modify the print statement (in step 4, page 10) to format the result to 2 decimal places along with a suitable format string as shown in the output below. Final balance: 112.36 12

Program CompoundInterest.py: function table Question 3: Problem statement Write a function table that requests an initial balance and a number of years and then prints out the two requested inputs together with some text to specify the meaning of the printout. For example, the initial balance could be printed out in the form The initial balance is 100 ukp The function table then prints out the final balance for the values -6%, -3%, 0%, 3%, 6% of the rate, given the requested initial balance and the requested number of years. Each value of the rate corresponds to a single line in the print out. For example, if the rate is -6% and the calculated balance is 126.7894 ukp, then the corresponding line of the printout is rate: -6%, balance: 126.79 ukp 13

Program CompoundInterest.py: function table (2) Two inputs required. Problem solving - Convert the pseudocode below into a sequence of Python statements in your program. 1. Use def to define a function named table that has no parameter variable, so the name should just be appended with a pair of brackets (). 2. Read in an initial balance that should be converted to a floatingpoint value, and store this value in a variable named initialbalance.* 3. Read in a number of years and store this value in a variable named numberyears. 4. Display the initial balance and the number of years together with some text to specify the meaning of the printout. An example is shown below for the variable initialbalance. print("the initial balance is %.2f ukp" % initialbalance) Hint *: Use the function input to firstly read in the balance, and then use the function float to convert the input string to a floating-point value. 14

Program CompoundInterest.py: function table (3) Align the print statements (step 4) and the for statement. The statements have the same indentation. Problem solving (continued) 5. Write a for statement to iterate over a range of values: -6, -3, 0, 3, 6, for the rate. Below is an outline of the algorithm needed to solve the given problem in the for loop body. for rate in range( Hint: use -6 as the start value and 3 as the step value. Work out the ending value yourself. ): # Call the function balance below to calculate the # balance for each rate value and store the result in b. b = complete the code to call the function balance together with the arguments: initialbalance, rate and numberyears # Add a print statement below to display a formatted # output of the rate and balance for each rate value. print( "define a format string that displays the rate and balance using two suitable format specifiers " % ( specify the two variables, rate and b, here ) ) 15

Program CompoundInterest.py: function table (4) Note The statements defined for steps 2 to 5 have the same level of indentation in the function body. Also the two statements in the for loop body have the same indentation. The string format operator % is covered in Week 5: Strings and Output. Provide a comment to explain the purpose of the function table. Include in your comment your name and the date. Test the function table using suitable values for the initial balance and the number of years. In order to test the function, you need to add a statement that calls the function i.e., table() The above statement must be defined outside of the function definition for table, and it is aligned with the function header. Save the function table in the file CompoundInterest.py and then run your program. 16

Supplementary Questions for Private Study The laboratory worksheet contains supplementary questions in section 4 for private study. You are encouraged to complete the supplementary questions at home, or in the laboratory if you have time after completing questions 2 to 3. 17