Python Basics PDF

Document Details

AmpleJudgment

Uploaded by AmpleJudgment

UNIV

Han-fen Hu

Tags

python programming computer programming coding beginner

Summary

This document is a Python Basics lecture or presentation. It covers topics like expressions, operators, variables, naming conventions, and data types. The author is Han-fen Hu.

Full Transcript

Python Basics Han-fen Hu Outline Expressions and Operators Data Type Naming Variables Assigning Data to a Variable Input and Output Converting Data Types 2 Expressions Most basic kind of programming instructio...

Python Basics Han-fen Hu Outline Expressions and Operators Data Type Naming Variables Assigning Data to a Variable Input and Output Converting Data Types 2 Expressions Most basic kind of programming instruction Components – 2 and 3 are values – + is the operator – 5 is the evaluated result It will be evaluated down to a single value 3 Operators (1) precedence 4 Operators (2) Multiplications and divisions are done before additions and subtractions, and then calculations take place from left to right. – 5+4*3-2/2 would evaluate to 5+(4*3)-(2/2) yielding 16. – 12/4*2 would evaluate to (12/4)*2 yielding 6. Exercise – 10/2+3*4 – 12-6/2*3+1 5 Operators (3) Use parentheses to override the usual precedence as needed Example – 10/ (2+3) *4 – (12-6)/2*(3+1) 6 Examples of Invalid Expressions 7 Data Types A data type is a category for values, Every value belongs to exactly one data type String is used for text values – Always surround your string in single quote (') characters 8 String Concatenation Meaning of an operator may change based on the data types of the values next to it. When + is used on two string values, it joins the strings as the string concatenation operator 9 Question How about the following statement? 10 Question (2) How about the following statement? 11 Question (3) How about the following statement? 12 String Replication When the * operator is used on one string value and one integer value, it becomes the string replication operator. 13 Question (4) How about the following statement? 14 Variables (1) 3 scoops = 3 scoops Variable: Temporary storage location in main memory – If you want to use the result of an evaluated expression later in your program, you can save it in a variable Reasons to use variables – Hold data that will be used later in the program – Allow for more precise treatment of numeric data – Enable code to run more efficiently 15 Naming Variables (1) Selecting a name for a variable: Variables are referred to by name – One single word – Can use only letters, numbers, and the underscore (_) character. – Can’t begin with a number. 32 characters is the recommended maximum number of characters to use Variable names are case-sensitive – Total, total, TOTAL and toTal are four different variables 16 Naming Variables (2) Valid names – janSales – sales2022 – westRegion – firstName – isValid – _total 17 Naming Variables (3) Invalid names & problems – 2ndQuarterSales Must begin with a letter or an underscore – West Region Cannot contain a space – first.Name Cannot contain punctuation – sales$North Cannot contain a special character – in-state Cannot contain a special character 18 Naming Variables (4) Guidelines for naming variables – Name should be descriptive Use meaningful names for variables to make programs easy to read. Avoid using abbreviations or acronyms that are not widely recognized. For example, use totalQuantitySold rather than tqs. – Use camel case: The first letter of a variable is lowercase, and the first letter of subsequent words, if any, are capitalized totalCost 19 averageRetailPrice Example A variable that contains an employee’s salary. – employeeSalary A variable that is used to store the name of the customer entered – customerName A variable that is used to represent the number of phones sold in last month – phoneSold 20 Exercise Name variables for the following data – A variable that represents the number of students in a university – A variable that is used to store the date of birth (for employees) – A variable that stores the duration of a project 21 Assigning Values to a Variable (1) Store values in variables with an assignment statement. – An assignment statement consists of a variable name, an equal sign (called the assignment – operator), and the value to be stored Syntax variableName = initialValue  Example unitPrice = 3.5 customerName = 'John' 22 Examples 1. Declare a variable for GPA and assign the value of 4.0. gpa= 4.0 2. Declare a number representing the number of students and assign the initial value as 30,000. numOfStudents = 30000 3. Declare a variable that represents the name of a brand. The brand is VegasYo. 23 branName = 'VegasYo' Assigning Values to a Variable (2) You can also assign value to variable at run time – When a variable is assigned a new value, the old value is forgotten Syntax: variableName = expression variableName = value Examples: commission = sales *.1 Multiplies the contents of the sales variable by 0.1 and then assigns the result to the commission variable population = 2.5 population = population * 1.003 24 Assigning Values to a Variable (3) Once a new value is assigned to the variable, the old value is forgotten 25 Example Create a program to simulate the sales at a ice cream shop – Input: Unit price and the number of scoops sold. – Output: Total amount due – Processing: 1. Get user input 2. Calculate the sales amount 3. Add the sales tax (tax rate as fixed 0.85%) 4. Show the total amount to the user 26 print() Function The print() function displays the string value inside the parentheses on the screen. – Notice that the quotes are not printed – The quotes are used to mark where the string begins and ends. 27 input() Function The input() function waits for the user to type some text on the keyboard and press enter – Note that the [*] shows the program is still running 28 Lab (1) Ice Cream Shop – Getting user input Variable Value Number of scoops ordered scoops Entered by the user Unit price of the ice cream unitPrice Entered by the user Sub total subTotal Sales tax salesTax 8.5 % Total cost totalCost 29 Converting Data Types (1) String data cannot be used as numeric values in calculation – Values entered using input() function are strings – On the other hand, numeric values cannot be printed directly in print() function Casting – Converting one data type to another – str(): convert numbers to string – int() and float(): convert string to number 30 Converting Data Types: Example (1) The + operator here concatenates the String. 31 Converting Data Types (2) Use the int() function to get the integer form of the variable then store this as the new value in the same variable creditJunior=input() creditJunior=int(creditJunior) Use the float() function in the same way to convert the string value to a float number 32 Converting Data Types: Example (2) The + operator here adds up the numbers. 33 Converting Data Types (3) If you want to concatenate an integer such with a string to pass to print(), use the str() function to convert the numeric number to a string total = creditJunior+creditSenior total = str(total) However, a numeric number alone can be used in print() without type conversion 34 Converting Data Types (4) Converting between numeric types – int to float: Widening the number range is fine – float to int: Lose some precision (digits after decimal point) – Note: if you need to round a number, use the round() function 35 Converting Data Types (5) Mixing different integer types in an expression is valid Floating-point real numbers can't be represented with exact precision due to hardware limitations 36 Lab (2) Ice Cream Shop – Completing the calculation Variable Value Number of scoops ordered scoops Entered by the user Unit price of the ice cream unitPrice Entered by the user Sub total subTotal Sales tax salesTax 8.5 % Total cost totalCost 37 MIS 740: Software Concepts Python Basic (1) Purpose Practice variable value assignment and use it in expressions Understand the input() and print() function. Create the first program. 1. Ice Cream Shop: Getting user input (1) Please create a new Notebook and name it as IceCreamShop. (2) Set the first cell as a markdown cell, so that we document the purpose, the author, and date for the program. Page 1 of 3 (3) Use the markdown cell to document for the program. To learn more about the markdown, see https://jupyter-notebook.readthedocs.io/en/stable/notebook.html#markdown-cells. (4) Insert a new cell below for the code. First, print the program purpose to the user, so that it is clear to the user: (5) To get users’ input, use the input() function, and assign the input to the variable. Page 2 of 3 2. Completing the calculation (6) Before calculating the subTotal, the variables scoops and unitPrice should be casted to numeric values. Similarly, before the totalCost can be printed, it should be casted to string. Please enter the following lines of code (7) Now you can run and test the program. Page 3 of 3 Python Basics (2) Han-fen Hu Outline Printing a Sequence of Numbers Format the Output math Modules Example 2 Printing a Sequence of Numbers In the print() function, we can print a series of numbers with a certain separator – The default separator is space – Use the keyword parameter "sep" in the print() function to define any string as the separator 3 String format() Method (1) Format string is a string which contains one or more format codes in text. – format() method of a string formats the specified value(s) https://www.python-course.eu/python3_formatted_output.php 4 String format() Method (2) Syntax: {argumentName: width.precision[type]} 5 String format() Method (3) Conversion Type s String f float d/i int 6 Format Strings Definition Examples :20s – String of 20 characters :10.3f – Float number with a total length of 10 (including decimal point) and 3 decimal places :6.1f – Float number, with a total length of 6 and 1 decimal place :,5d – Integer number with thousands separator and a total length of 5 7 Format String: Examples (1) Use , (comma) in the format string to indicate the thousands separators 8 Format String: Examples (2) 9 Format String: Examples (3) 10 Format String: Examples (4) Use strings with the formatter 11 Lab (1) Ice Cream Shop – Formatting the result Variable Value Number of scoops ordered scoops Entered by the user Unit price of the ice cream unitPrice Entered by the user Sub total subTotal Sales tax salesTax 8.5 % Total cost totalCost 12 Importing math Modules (1) Python has many auxiliary functions for calculations with numbers You can refer to the Python documentation for more details https://docs.python.org/3/library/math.html 13 Importing math Modules (2) Syntax – round(number, digits) – returns a float number that is a rounded version of the specified number, with the specified number of decimals – Default digits is 0 14 Example Land Price Calculator – Please create an application calculating the price of an area. The user enters the length and width of the area in feet and enters the price per acre of land. The program should show the area in square foot, acre, and the total price. Note: One acre of land is equivalent to 43,560 square foot 15 Exercise BMI Calculator – Please write a program that calculates the body mass index (BMI) for an individual given the height in inches and weight in pounds. To convert the height in inches to meters, please divide the length value by 39.37. To convert the weight in pounds to kilograms, please divide the value by 2.205. – Please format the result with one digit after the decimal point. 16 MIS 740: Software Concepts Python Basic (2) Purpose Practice variable value assignment and use it in expressions Understand the input() and print() function. Get Familiar with the string formatter Get familiar with the string formatter 1. Format the output (1) In the IceCreamShop program, the output was not formatted. Revise the last line of code to incorporate the formatting string (2) Run the program to see the difference. 2. Example: Land Price Calculator Please create an application calculating the price of an area. The user enters the length and width of the area in feet, and enters the price per acre of land. The program should show the area in square foot, acre, and the total price. Note: One acre of land is equivalent to 43,560 square feet. (3) Please download LancPriceCalculator.ipynb from WebCampus. Page 1 of 4 (4) At the home page of Jupyter Notebook, browser to the folder where you would like to save the file. Click on upload at the upper right corner. (5) Browser to where you save LancPriceCalculator.ipynb, select and open it. Page 2 of 4 (6) Click and open the file. (7) First, let’s get the user input. We can use the float() function with the input() to convert the input string to a float number. (8) Now we can calculate the area in squared feet. (9) In order to display the result properly, define a formatter Page 3 of 4 (10) Then use the formatter in the print() funtion to print the areInSqFt. (11) Please do the same to format areaInAcre and totalPrice. 3. Exercise: BMI Calculator Please write a program that calculates the body mass index (BMI) for an individual given the height in inches and weight in pounds. To convert the height in inches to meters, please divide the length value by 39.37. To convert the weight in pounds to kilograms, please divide the value by 2.205. – Formula: weight (kg) / [height (m)]2 Please format the result with one digit after decimal point. Page 4 of 4 Flow Control (1): Decision Structure Han-fen Hu Outline Overview of decision structure Boolean values Comparison operators Logical operators Nested selection structure 2 Example Kanton Boutique wants an application that allows the store clerk to enter an item’s price and the quantity purchased by a customer. – The application should calculate the total amount the customer owes by multiplying the price by the quantity purchased and then subtracting any discount. – It then should display the total amount owed. – Kanton Boutique gives customers a 10% discount when the quantity purchased is over five; – Otherwise, it gives a 5% discount. 3 Algorithm Input: price and quantity purchased Output: total owed Process: 1. Get user input and assign to variables 2. Total owed = price * quantity 3. If the quantity is over 5 discount rate = 0.1 Otherwise, discount rate = 0.05 4. discount = total owed * discount rate 5. total owed = total owed – discount 6. display the total owed to the user 4 Flow Chart 5 Syntax and Sample Code 6 Boolean Values Boolean data type has only two values – True and False – In Python code, the Boolean values True and False lack the quotes An expression can be evaluated into True or False – With comparison operators – Used in decisions to determine the path/route of the algorithm 7 Comparison Operators (1)  Also called Relational Operators  Used to compare two values  Always result in a True or False value Operator What it means Examples > greater than if roomCapacity > enrollment: < less than if dateDue < date.today(): >= greater than or equal to if examScore >= 90: =2.5): and Both expressions are always evaluated if (act = y 2. (x >= y) or (y == 30) 3. not ((y - x == 5) and (x > 0)) 15 Exercise: Logic Operator (2) The company have stores in IL, IN, and KY. – The program allow users to enter the state and store the value in state – The program display result “We have a store in this state” or “We do not a store in this state” – Valid states: IL, IN, KY (Assume the user enter the string in all capitalized letters) 16 Exercise: Logic Operator (2) # get user input state = input(); # Make the decision if : result = " else: result = print(result) 17 elif Statements (1)  In the case where you want one of many possible clauses to execute.  The elif statement is an “else if” statement that always follows an if or another elif statement 20 elif Statements (2) 21 elif Statements (3) Optionally, you can have an else statement after the last elif statement. – It is guaranteed that at least one (and only one) of the clauses will be executed. 22 Lab (1) Grade Converter This program accepts a score between 0- 100, and convert it to a letter grade 91~100 A 81~90 B 71~80 C 0~70 F other invalid 23 Nested Structure if the customer orders a cup of coffee: ask the customer if he/she wants regular or decaffeinated coffee if the customer wants regular coffee: pour regular coffee into a cup Nested if.. else structure else: pour decaffeinated coffee into a cup else: ask the customer for what of drink they need Indentation is important! It shows the range of the statements to be executed under the condition 24 Nested Decision Structure: Example (1) 25 Flow Chart 1 26 Flow Chart 2 27 Lab (2) Voter Information In this program, the user will enter the age, and answer whether he/she is registered to vote. The application then should show proper message to the user. 28 Nested Decision Structure: Example (2) 29 Lab (3) Payment Calculator This program calculates and displays the monthly payment on a car loan. To make the calculation, the application must know the loan amount (principal), the annual percentage rate (APR) of interest, and the life of the loan (term) in years. – Loan amount should positive – APR should be less than 1 – Term should be more than 1 30 Exercise Dog Age Estimator Please write a program that estimates a dog's age in human years, according to the following table Dog Age Human Year 0 0~14 1 15 2 24 3 28 4 32 5 37 >5 Human year unknown 31 MIS 740: Software Concepts Flow Control (1): Decision Structure Purpose Get familiar with decision structure (if.. elif… else) Practice solving problem with nested structure 1. Preparation (1) Please download 04_lab files.zip from WebCampus. (2) Unzip the file. For Windows users, you can right-click on the downloaded zip file and select “Extract All) For Mac users, you can right-click on the downloaded zip file and select “Open With\Archive Utility” (3) Create a new folder in Jupyter Notebook home page. (4) Upload the.ipynb files (from the extracted zip file) to the folder. Page 1 of 4 2. Grade Converter (5) Please open the partially completed program GradeConverter.ipynb. The program checks whether the score is valid (i.e., between 0 and 100). (6) To check the next condition, we can use elif here, since this condition will be checked only when the previous condition is evaluated to False. Please complete the other conditions. (7) The last clause can be just the else statement. It represents the last possibility. (8) You can now run and test the program. Page 2 of 4 3. Voter Information (9) Please open VoterInformation.ipynb. The age condition has been verified. Please complete the section for checking registration status: 4. PaymentCalculaor (10) Please open PaymentCalculator.ipynb. In this program, we need to first verify users’ input for principal. (11) Next, verify the interest rate (APR) (12) Similarly, verify the term. Only when it is valid, calculate the monthly payment. Page 3 of 4 (13) In this example, the program uses the nested decision structure. Exercise (14) Please open Dog Age Estimator Please write a program that estimates a dog's age in human years, according to the following table Dog Age Human Year 0 0~14 1 15 2 24 3 28 4 32 5 37 >5 Human year unknown Page 4 of 4 Flow Control (2): Iteration Structure Outline Overview of Iteration Structure while loop Use while Loop for Input Validation Nested Structure for Loop 2 Repeating Program Instructions (1) Iteration structure (or loop) – Repeatedly processes instructions until condition is met – Example: “Make hay while the sun shines” Looping condition – The requirement for repeating the instructions – In above example: “while the sun shines” 3 3 Repeating Program Instructions (2) 4 Repeating Program Instructions (3) Iteration structure should contain the following components – Initial condition – Stop condition, and – How the move from initial condition to the stop condition 5 while Loop (1) Syntax while condition: loop body instructions  Example 6 while Loop (2) While the condition is true, the statements will execute repeatedly. – The while loop is a pretest loop, which means that it will test the value of the condition prior to executing the loop. – A while loop executes 0 or more times. If the condition is false, the loop will not execute. 7 while Loop Flow Chart true Boolean statement(s) expression false do-while Loop Flowchart 8 Comparing if and while Statements (1) Initial condition if statement while statement Stop condition Move from Initial condition to Stop condition 9 Comparing if and while Statements (2) if statement while statement 10 Counters/Accumulators Infinite loop – Also called endless loop – The condition to end the loop is never met – Care must be taken to set the condition to false somewhere in the loop so the loop will end. Counters/Accumulators – Initializing: Assigning beginning value – Updating: Adding a number to counter/accumulator’s value (positive or negative) – Done within the loop body 11 Arithmetic Assignment Operators (1) Used to abbreviate an assignment statement: – Containing an arithmetic operator Format – variableName Operator value Operators += addition assignment -= subtraction assignment *= multiplication assignment 12 /= division assignment Arithmetic Assignment Operators (2) 13 Arithmetic Assignment Operators (3) Example 1 age = age +1 can be abbreviated as age +=1 Example 2 price = price – discount can be abbreviated as price -= discount Example 3 sales = sales * 1.05 can be abbreviated as sales *= 1.05 14 Exercise (1) What will the following code display? Initial condition Stop condition Move from Initial condition to Stop condition 15 Exercise (2) The following code should display the numbers 1 through 4, but it is not working correctly. Correct the code. 16 Lab (1) Rainfall Average The user would enter the inches of rainfall for each month. The program should display the total inches of rainfall, and the average rainfall per month 17 Use while Loop for Input Validation (1) After the initial input, use a while loop to validate the input and repeat until the input is valid In this case, the condition for the while 18 loop should be the “invalid value” Lab (2) Soccer Team This program calculates the number of soccer teams that a youth league may create from the number of available players. Input validation is demonstrated with while loops. The program will ask the user to enter the number of players per team (between 9 and 15), and the available number of players. The program will return how many teams the players and form and how many players are left. 19 Use while Loop for Input Validation (2) We can also initialize the variable to an invalid value so that the while loop will be execute 20 Lab (3) Soccer Team Please revise the SoccerTeam program to try out the second method of input validation 21 Sentinel Values Sometimes the end point of input data is not known. A sentinel value can be used to notify the program to stop acquiring input. If it is a user input, the user could be prompted to input data that is not normally in the input data range (i.e. –1 where normal input would be positive.) Programs that get file input typically use the end-of-file marker to stop acquiring input data. 22 Lab (4) Soccer Point Keeper The program calculates the total number of points a soccer team has earned over a series of games. The user enters a series of point values, then -1 when finished. 23 Nested Structure (1) while statement can be nested in if..else statements Proper indentation is critical – One of the most distinctive features of Python is its use of indentation to mark blocks of code 24 Lab (5) – Multiples Finder In this program, the user will enter a number to find the multiples and also enter a range (with start and end values). The program should then show all the multiples of the chosen number between start and end values. – For example, given magicNum = 7, start = 22, end = 40, the result should be 28, 35 – Error Checking – start should not be greater than end – magicNum should not be greater than end 25 Nested Structure (2) 26 for Loop (1)  for loop – Is used to code a range-controlled loop – Processes instructions precise number of times  Syntax for counter in range (start, end, step): statements – Specify (1) start value, (2) end value, and (3) step value – Start value and end value provide looping range » When start value is omitted, it is set to 0 » The end value is excluded – Step value increments or decrements counter » When step value is omitted, it is set to 1 27 for Loop (2) Example 1 Example 2 28 Question What will the following code display? * * * ! 29 for Loop (3) The start, end, and step values can be variables The start, end, and step values should be integer. When we need to use float number, we need to use the numpy.arange() 30 Lab (6) QuarterlyExpense The program asks the user to enter the expense for each quarter, after the data for the four quarters are entered, show the total and average. 31 Comparing for and while Loops (1) (0,5,1) The for loop is equivalent to the following while loop Start: i=0 End: i < 5 (exclude 5) Step: i+1 32 Comparing for and while Loops (2) Either can be used to code counter- controlled loop When using a while loop: – Must declare and initialize the counter variables – And update the counter variable – Include the appropriate comparison in the while clause When using for loop – Declaration, initialization, comparison and update are handled by the for clause 33 Comparing for and while Loops (3) However, for loop cannot be used for – Input validation – Use sentinel value to end the loop 34 Nested Iteration Structures Inner loop placed entirely within outer loop Inner loop is referred to as nested loop 35 Lab (7) BudgetSummary The program would summarize the quarterly budget of a firm for a few numbers of years. The quarterly budget amounts are entered. The program should show the average annual and quarterly budget amount. 36 MIS 740: Software Concepts Flow Control (2): Iteration Structure Purpose Use while loop in the code Practice solving problem with nested structure Use for loop in the code 1. Preparation (1) Please download 05_lab files.zip from WebCampus. Unzip the files, and import them to Jupyter Notebook. 2. Rainfall Average (2) Please open RainfallAverage.ipynb The user would enter the inches of rainfall for each month. The program should display the total inches of rainfall, and the average rainfall per month. Please complete the program as following: (3) You can run and test the program. Please try to enter 0 as the number of months. What would happen? How to fix the issue? 3. Soccer Team (4) Please open SoccerTeam.ipynb. This program calculates the number of soccer teams that a youth league may create from the number of available players. Input validation is demonstrated with while loops. The program will ask the user to enter the number of players per team (between 9 and 15), and the available number of players. The program will return how many teams the players and form and how many players are left. Page 1 of 6 (5) First, get the teamSize from the user. Then use a while to validate whether the value is invalid. If the valid is not valid, ask for input again. (6) Similarly, validate the input for the number of players: (7) When the two values are valid, we can now do the math. (8) Show how many players are left when leftOver is not 0. 4. Soccer Point Keeper (9) Please open SoccerPointKeeper.ipynb The program calculates the total number of points a soccer team has earned over a series of games. The user enters a series of point values, then -1 when finished. Page 2 of 6 (10) As long as the entered value is not -1, the program asks for input and add the value to total. (11) Can you revise the program so that the program shows the average points per game as the result? 5. Multiples Finder (12) Please open MultiplesFinder.ipynb In this program, the user will enter a number to find the multiples and also enter a range (with start and end values). The program should then show all the multiples of the chosen number between start and end values. First, complete the error checking. The nested if statements verifies two conditions: start should not be greater than end magicNum should not be greater than end Page 3 of 6 (13) Please complete the two conditions: (14) Once passing the error checking, we can start working on the repetition structure. It should begin with the initial condition, specify the stop condition, and how the move from initial condition to the stop condition. (15) Please complete the code: (16) For each candidateNum, we need to decide whether it is a multiple of the magicNum. (17) Now the program is complete. Read through it again and test it. Page 4 of 6 6. QuarterlyExpense (18) Please open QuarterlyExpense.ipynb. The program asks the user to enter the expense for each quarter, after the data for the four quarters are entered, show the total and average. Please complete the for loop to get the expense for each month: (19) Run and test the program. 7. BudgetSummary (20) Please open BudgetSummary.ipynb The program would summarize the quarterly budget of a firm for a few numbers of years. The quarterly budget amounts are entered. The program should show the average annual and quarterly budget amount. Please fill in the for loop and the prompt text: (21) You can also do it in another way: Page 5 of 6 (22) Please also add input validation for numOfYears, so that only when it is a positive number, the program proceeds to get the budget amounts from the user: (23) Please also add the input validation for amount. Only when it is a positive number, the program proceeds to ad the amount to total: (24) You can now run and test the program. Page 6 of 6 Functions Outline Definition of Functions Parameters Return Values Scope of Variables Top-down Design 2 Overview of Function A mini-program within a program – Block of program code that performs specific task – A Program unit that performs a sub-task Why functions? – Divide and conquer: Top-down design – Re-use A function can be used in multiple programs Group code that gets executed multiple times 3 Example of Functions print() input() randint() round() etc. 4 Creating a Function(1) Syntax def function_name([parameter list]): statements –statements represent the body of the function –This code is executed when the function is called, not when the function is first defined 5 Creating a Function: Example (1) Function Definition Function Calls 6 Creating a Function: Example (2) 7 Avoid Duplicating Code Faster in development – Not copy-and-pasting the code Increased maintainability Improved readability of the code Reducing error 8 Naming Functions Descriptive of the purpose Verbs or Verb phrases Lowercase letters Use an underscore to separate words in a function name 9 Invoking a Function (1) Call statement: Invokes functions Syntax function_name ([argumentList]); – function_name : Name of function to be invoked – argumentList: Optional list of arguments to pass 10 Invoking a Function (2) 11 Passing Variables as Parameters (1) The variables passed to a function are the “input” for the function – Taken the input, the function processes and generate the output The value stored in a parameter is forgotten when the function returns 12 Passing Variables as Parameters (2) 13 Passing Variables as Parameters (3) 14 Passing Variables as Parameters (3) Parameters are variables available within the function The values passed to the function are called arguments – A parameter is a variable that an argument is stored in when a function is called The order of the variables matters The names of the variables and parameters do not need to be the same 15 Passing Variables as Parameters (3) 16 Lab (1) Credit Card Approval In this program, the user will enter the salary and the credit rating, the program will then show the application is approved or not. When the salary is no less than 20,000 and the credit rating is greater than 600, the application will be approved 17 Return Value (1) A function returns a value to the calling statement after completing its task – The returning value is the “output” of a function Syntax def function_name([parameter list]): Statements return value 18 Return Value: Example (1) 19 Calling a Function with Returning Value (1) Example 1 – assigning the return value to a variable newPrice = get_new_price(currentPrice) Example 2 – using the return value in a calculation totalDue = quantity* get_new_price(currentPrice) Example 3 – displaying the return value print(str(get_new_price(currentPrice)) 20 Return Value (2) When an expression is used with a return statement, the return value is what this expression evaluates to – The returned value can be assigned to a variable – The returned value can be used in a print() – The returned value can be used in an expression Equivalent!! 21 Calling a Function with Returning Value (2) 22 Calling a Function with Returning Value (3) 23 Designing a Function Determine Output Identify Input Determine process necessary to turn given Input into desired Output Passed variables Returning Value 24 Lab (2) Gross Pay Calculator This application calculates gross pay based on the hours and rate selected by the user. – This program also uses the while loop to validate user input 25 Exercise (1) MetricConverter The program that converts the distance in meters to kilometers, inches, or feet. The program will ask the user to enter a distance in meters, and then make the choice of converting to kilometers, inches, or feet. The program then displays the result based on the user’s choice 26 Return Value as a Boolean The return type of a function can be Boolean The function then can be used as a Boolean expression for the if statement, or while condition 27 Lab (3) Account Status Check This program determines whether the service fee can be waived for a bank customer. The service charge can be waived if (1) the total balance is no less than 50,000, or, (2) the account is more than 10 years, and the total balance is greater than 8,000. 28 Exercise (2) CreditCardApproval (1) Please revise the program so that check_qualification() function returns a Boolean value (2) Revise the main program accordingly to show the messages to the user 29 Scope of Variables (1) Local variables – Parameters and variables that are assigned in a function – Exist in that function’s local scope – Local variables are destroyed (forgotten) after the function call is finished and returned Global variables – Variables that are assigned outside all functions – Exist in the global scope – Global variables are destroyed only after the entire program ends A variable is one or the other 30 Scope of Variables: Example (1) restingRate, age, and trainingRate are local to the function restingRate, age, and trainingRate cannot be used in the global scope userAge, restingHeartRate, and result are global to the program 31 Scope of Variables (2) Code in the global scope cannot use any local variables. – However, a local scope can access global variables Code in a function’s local scope cannot use variables in any other local scope You can use the same name for different variables if they are in different scopes 32 Scope of Variables: Example (2) restingRate, age, and trainingRate cannot be used in compute_max_rate() targetRate and maxRate cannot be used in compute_training_rate() 33 Why Scopes? Narrow down the list code lines that may be causing a bug – When variables are modified by the code in a particular call to a function, the function interacts with the rest of the program only through its parameters and the return value – Difficult to track down a bad value when everything is global scope Make the code more manageable Divide and conquer 34 Scope of Variables (3) Local and global variables with the same name – Legal and correct syntax-wise – The local variables will take precedence within a function Confusing! Avoid using the same variable name in different scopes 35 Scope of Variables: Example (3) 36 Top-down Design (1) Program Flow 37 Top-down Design (2) Each function should be cohesive – Do a single well-defined task. Each function should be as reusable as possible – Keep the task simple Pass a variable only when it is used in the receiving function 38 An Undesirable Design Program Flow 39 MIS 740: Software Concepts Functions Purpose Define functions with parameters and return value Use functions in the program 1. Preparation (1) Please download 08_lab files.zip from WebCampus. Unzip the files, and import them to Jupyter Notebook. 2. Credit Card Approval (2) In this program, the user will enter the salary and the credit rating, the program will then show the application is approved or not. When the salary is no less than 20,000 and the credit rating is greater than 600, the application will be approved. Please define the function as shown below: Page 1 of 3 3. Gross Pay Calculator (3) This application calculates gross pay based on the hours and rate selected by the user. Please first define the function calculate_gross_pay(hours, rate). It should return a value representing the gross pay. (4) Then in the program, call the function and use it in the print() function. Please note that the returning value is a float value. Thus str() should be used to convert the data type. (5) Please note that this program uses while loops to validate users’ input. When invalid values are entered, the program will repeat and ask the user to enter again. Page 2 of 3 Exercise (1): MetricConverter The program converts the distance in meters to kilometers, inches or feet. The program will ask the user to enter a distance in meters, and then make the choice of convert to kilometers, inches, or feet. The program then display the result based on user’s choice: kilometer = meters * 0.001 inches = meters * 39.37 feet = meters * 3.281 Please make sure that you define a function for this program. 4. Account Status Check (6) This program determines whether the service fee can be waived for a bank customer. The service charge can be waived if (1) the total balance is no less than 50,000, or, (2) the account is more than 10 years and the total balance is greater than 8,000. First, please define the is_waived() function, which will return a Boolean value. (7) Please complete the if statement by calling the is_waived() function. Exercise (2): CreditCardApproval (8) Please revise the CreditCardApproval program (a) Let check_qualification() function return a Boolean value (b) Revise the main program accordingly to show the messages to the user Page 3 of 3

Use Quizgecko on...
Browser
Browser