Introduction to Pattern Matching
Introduction to Pattern Matching
Foundations to Matching a Case
Introduction
We know that a conditional statement is used to apply some condition(s) to a value to check something as being True or False and then take an action based on the outcome. An enhanced way to perform such an operation is to check whether a certain value matches one or more condition. This is the basis for pattern matching.
Practical Learning: matching a String
print("==========================================") print(" - Amazing DeltaX - State Income Tax -") print("==========================================") stateName = "" taxRate = 0.00 print("Enter the information for tax preparation") print("States") print(" AK - Alaska") print(" AR - Arkansas") print(" CO - Colorado") print(" FL - Florida") print(" GA - Georgia") print(" IL - Illinois") print(" IN - Indiana") print(" KY - Kentucky") print(" MA - Massachusetts") print(" MI - Michigan") print(" MO - Missouri") print(" MS - Mississippi") print(" NV - Nevada") print(" NH - New Hampshire") print(" NC - North Carolina") print(" PA - Pennsylvania") print(" SD - South Dakota") print(" TN - Tennessee") print(" TX - Texas") print(" UT - Utah") print(" WA - Washington") print(" WY - Wyoming") abbr = input("\nEnter State Abbreviation: ") print("--------------------------------------------") grossSalary = float(input("Gross Salary: ")) taxAmount = grossSalary * taxRate / 100.00 netPay = grossSalary - taxAmount; print("============================================") print(" - Amazing DeltaX - State Income Tax -") print("--------------------------------------------") print(F"Gross Salary: {grossSalary:6.2f}") print(F"State: {stateName}") print(F"Tax Rate: {taxRate:6.2f}%") print("--------------------------------------------") print(F"Tax Amount: {taxAmount:6.2f}") print(F"Net Pay: {netPay:6.2f}") print("============================================")
========================================== - Amazing DeltaX - State Income Tax - ========================================== Enter the information for tax preparation States AK - Alaska AR - Arkansas CO - Colorado FL - Florida GA - Georgia IL - Illinois IN - Indiana KY - Kentucky MA - Massachusetts MI - Michigan MO - Missouri MS - Mississippi NV - Nevada NH - New Hampshire NC - North Carolina PA - Pennsylvania SD - South Dakota TN - Tennessee TX - Texas UT - Utah WA - Washington WY - Wyoming Enter State Abbreviation: FL -------------------------------------------- Gross Salary: 1558.85 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- Gross Salary: 1558.85 State: Tax Rate: 0.00% -------------------------------------------- Tax Amount: 0.00 Net Pay: 1558.85 ============================================ Press any key to continue . . .
========================================== - Amazing DeltaX - State Income Tax - ========================================== Enter the information for tax preparation States AK - Alaska AR - Arkansas CO - Colorado FL - Florida GA - Georgia IL - Illinois IN - Indiana KY - Kentucky MA - Massachusetts MI - Michigan MO - Missouri MS - Mississippi NV - Nevada NH - New Hampshire NC - North Carolina PA - Pennsylvania SD - South Dakota TN - Tennessee TX - Texas UT - Utah WA - Washington WY - Wyoming Enter State Abbreviation: KY -------------------------------------------- Gross Salary: 1558.85 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- Gross Salary: 1558.85 State: Tax Rate: 0.00% -------------------------------------------- Tax Amount: 0.00 Net Pay: 1558.85 ============================================ Press any key to continue . . .
A Case for a Conditional Selection
In a typical application, you have many comparisons to make. Some comparisons involve many variables but some comparisons are performed on only one variable. As a result, you may have a situation where you want to compare one variable to many values. To do that, you can create a list of comparisons, then select which outcome applies to the conclusion you need to establish.
To perform a series of comparisons of one variable with one or more values, you use a keyword named match. Like most comparison operators, including if that we saw in previous lessons, the match keyword requires parentheses, as in match(). In the parentheses, you must type the existing name of the variable on which you want to perform comparisons. After the parentheses, type a colon the same way we saw for the if conditional statement. The section after the colon of match(): is referred to as the body of the match() conditional statement. In that body, you must create one or more sections that would perform the necessary selections. Each section is created with a keyword named case. As a result, the primary formula to perform matching is:
match(expression): case choice1: statement1 case choice2: statement2; case choice-n: statement-n
Each section of a matching pattern starts with the case keyword. The case keyword is followed by a constant value (or an expression). That value is followed by a colon that all Python conditional statements use. The section from the colon to the next case or from the colon to the end of the matching patter is referred to as the body of the case statement. In that body, the operations of a case are performed.
Matching an Integer
Probably the most regularly used type of value in a match expression is a natural number. The object or expression passed to the match can come from any source as long as it represents a constant integer. Consider the following code that uses an if conditional statement:
number = 248
conclusion = "That number is not right."
if number == 248:
conclusion = "That number is correct."
print(conclusion)
print("========================================")
This would produce:
That number is correct. ======================================== Press any key to continue . . .
The same code can be written with a match statement as follows:
number = 248
conclusion = "That number is not right."
match number:
case 248:
conclusion = "That number is correct."
print(conclusion)
print("========================================")
We know that an if conditional statement can use one or more else options. Here is an example:
incomeTax = 0.00
print("Payroll Evaluation")
print("============================================")
print("Enter the information to evaluate taxes")
print("Frequency by which the payroll is processed:")
print("1 - Weekly")
print("2 - Biweekly")
print("3 - Semimonthly")
print("4 - Monthly")
frequency = int(input("\nEnter Payroll Frequency: "))
print("--------------------------------------------")
grossSalary = float(input("Gross Salary: "))
if frequency == 1:
incomeTax = 271.08 + (grossSalary * 24 / 100)
elif frequency == 2:
incomeTax = 541.82 + (grossSalary * 24 / 100)
elif frequency == 3:
incomeTax = 587.12 + (grossSalary * 24 / 100)
elif frequency == 4:
incomeTax = 1174.12 + (grossSalary * 24 / 100)
print("============================================")
print("Payroll Evaluation")
print("--------------------------------------------")
print("Gross Salary:%19s" % grossSalary)
print("Income Tax:%21.2f" % incomeTax)
print("============================================")
Here is an example of executing the code:
Payroll Evaluation ============================================ Enter the information to evaluate taxes Frequency by which the payroll is processed: 1 - Weekly 2 - Biweekly 3 - Semimonthly 4 - Monthly Enter Payroll Frequency: 1 -------------------------------------------- Gross Salary: 1558.93 ============================================ Payroll Evaluation -------------------------------------------- Gross Salary: 1558.93 Income Tax: 645.22 ============================================ Press any key to continue . . .
In the same way, a match statement can use many cases. Here is an example:
incomeTax = 0.00 print("Payroll Evaluation") print("============================================") print("Enter the information to evaluate taxes") print("Frequency by which the payroll is processed:") print("1 - Weekly") print("2 - Biweekly") print("3 - Semimonthly") print("4 - Monthly") frequency = int(input("\nEnter Payroll Frequency: ")) print("--------------------------------------------") grossSalary = float(input("Gross Salary: ")) match frequency: case 1: incomeTax = 271.08 + (grossSalary * 24 / 100) case 2: incomeTax = 541.82 + (grossSalary * 24 / 100) case 3: incomeTax = 587.12 + (grossSalary * 24 / 100) case 4: incomeTax = 1174.12 + (grossSalary * 24 / 100) print("============================================") print("Payroll Evaluation") print("--------------------------------------------") print("Gross Salary:%19s" % grossSalary) print("Income Tax:%21.2f" % incomeTax) print("============================================")
Matching a String
Besides a natural number, a match statement can perform its case comparisons on a string value, such as a variable that holds a string value or an expression that produces a string. This means that each case must consider a possible value that the variable or expression may hold.
Practical Learning: matching by Some Strings
print("==========================================")
print(" - Amazing DeltaX - State Income Tax -")
print("==========================================")
stateName = ""
taxRate = 0.00
print("Enter the information for tax preparation")
print("States")
print(" AK - Alaska")
print(" AR - Arkansas")
print(" CO - Colorado")
print(" FL - Florida")
print(" GA - Georgia")
print(" IL - Illinois")
print(" IN - Indiana")
print(" KY - Kentucky")
print(" MA - Massachusetts")
print(" MI - Michigan")
print(" MO - Missouri")
print(" MS - Mississippi")
print(" NV - Nevada")
print(" NH - New Hampshire")
print(" NC - North Carolina")
print(" PA - Pennsylvania")
print(" SD - South Dakota")
print(" TN - Tennessee")
print(" TX - Texas")
print(" UT - Utah")
print(" WA - Washington")
print(" WY - Wyoming")
abbr = input("Enter State Abbreviation: ")
print("--------------------------------------------")
grossSalary = float(input("Gross Salary: "))
match (abbr):
case "CO":
taxRate = 4.63
stateName = "Colorado"
case "FL":
taxRate = 0.00
stateName = "Florida"
case "IL":
taxRate = 4.95
stateName = "Illinois"
case "IN":
taxRate = 3.23
stateName = "Indiana"
case "KY":
taxRate = 5.00
stateName = "Kentucky"
case "MA":
taxRate = 5.00
stateName = "Massachusetts"
case "MI":
taxRate = 4.25
stateName = "Michigan"
case "NC":
taxRate = 5.25
stateName = "North Carolina"
case "NH":
taxRate = 5.00
stateName = "New Hampshire"
case "NV":
taxRate = 0.00
stateName = "Nevada"
case "PA":
taxRate = 3.07
stateName = "Pennsylvania"
case "TN":
taxRate = 1.00
stateName = "Tennessee"
case "TX":
taxRate = 0.00
stateName = "Texas"
case "UT":
taxRate = 4.95
stateName = "Utah"
case "WA":
taxRate = 0.00
stateName = "Washington"
case "WY":
taxRate = 0.00
stateName = "Wyoming"
taxAmount = grossSalary * taxRate / 100.00
netPay = grossSalary - taxAmount;
print("============================================")
print(" - Amazing DeltaX - State Income Tax -")
print("--------------------------------------------")
print(F"Gross Salary: {grossSalary:6.2f}")
print(F"State: {stateName}")
print(F"Tax Rate: {taxRate:6.2f}%")
print("--------------------------------------------")
print(F"Tax Amount: {taxAmount:6.2f}")
print(F"Net Pay: {netPay:6.2f}")
print("============================================")
========================================== - Amazing DeltaX - State Income Tax - ========================================== Enter the information for tax preparation States AK - Alaska AR - Arkansas CO - Colorado FL - Florida GA - Georgia IL - Illinois IN - Indiana KY - Kentucky MA - Massachusetts MI - Michigan MO - Missouri MS - Mississippi NV - Nevada NH - New Hampshire NC - North Carolina PA - Pennsylvania SD - South Dakota TN - Tennessee TX - Texas UT - Utah WA - Washington WY - Wyoming Enter State Abbreviation: CO -------------------------------------------- Gross Salary: 1558.85 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- Gross Salary: 1558.85 State: Colorado Tax Rate: 4.63% -------------------------------------------- Tax Amount: 72.17 Net Pay: 1486.68 ============================================ Press any key to continue . . .
========================================== - Amazing DeltaX - State Income Tax - ========================================== Enter the information for tax preparation States AK - Alaska AR - Arkansas CO - Colorado FL - Florida GA - Georgia IL - Illinois IN - Indiana KY - Kentucky MA - Massachusetts MI - Michigan MO - Missouri MS - Mississippi NV - Nevada NH - New Hampshire NC - North Carolina PA - Pennsylvania SD - South Dakota TN - Tennessee TX - Texas UT - Utah WA - Washington WY - Wyoming Enter State Abbreviation: KY -------------------------------------------- Gross Salary: 1558.85 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- Gross Salary: 1558.85 State: Kentucky Tax Rate: 5.00% -------------------------------------------- Tax Amount: 77.94 Net Pay: 1480.91 ============================================ Press any key to continue . . .
Primary Topics on Pattern Matching
Introduction
We saw that a match conditional statement can process natural numbers and strings. It can also process Boolean values or logical expressions. To proceed, you can write a Boolean variable or an expression that produces a Boolean value in the parentheses of match(). Then, one case can consider a True value and another case would consider a False value. Here is an example:
conclusion = '' emplTitle = "Manager" emplIsManager = emplTitle == "Manager" match emplIsManager: case True: conclusion = "The employee is a manager." case False: conclusion = "The staff member is a regular employee." print(conclusion); print("========================================")
This would produce:
The employee is a manager. ======================================== Press any key to continue . . .
Matching a Boolean Expression
In the previous example, in the parentheses of match(), we included a variable that held a Boolean value. As an alternative, you can include a Boolean expression. Here is an example:
conclusion = ''
emplTitle = "Manager"
match emplTitle == "Manager":
case True:
conclusion = "The employee is a manager."
case False:
conclusion = "The staff member is a regular employee."
print(conclusion)
print("========================================")
Otherwise, all the other comparison operators we studied can also be used. Here is an example:
timeWorked = 30.00
# If TimeWorked >= 40
match timeWorked >= 40.00:
case True:
print("The employee works full-time.")
case False:
print("The staff member worked part-time.")
print("========================================")
The main idea is to know how to convert an if conditional statement that uses a logical expression such as this:
print("FUN DEPARTMENT STORE")
print("=======================================================")
print("Payroll Preparation")
print("-------------------------------------------------------")
print("Enter the following pieces of information")
print("-------------------------------------------------------")
print("Employee Information")
print("-------------------------------------------------------")
firstName = input("First Name: ");
lastName = input("Last Name: ");
hSalary = float(input("Hourly Salary: "))
print("-------------------------------------------------------")
print("Time worked")
print("-------------------------------------------------------")
mon = float(input("Monday: "))
tue = float(input("Tuesday: "))
wed = float(input("Wednesday: "))
thu = float(input("Thursday: "))
fri = float(input("Friday: "))
timeWorked = mon + tue + wed + thu + fri
regTime = 0.00
overtime = 0.00
regPay = 0.00
overPay = 0.00
if timeWorked <= 40.00:
regTime = timeWorked
regPay = hSalary * timeWorked
overtime = 0.00
overPay = 0.00
else:
regTime = 40.00
regPay = hSalary * 40.00
overtime = timeWorked - 40.00
overPay = hSalary * 1.50 * overtime
netPay = regPay + overPay
print("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+")
print("FUN DEPARTMENT STORE")
print("=======================================================")
print("Payroll Evaluation")
print("=======================================================")
print("Employee Information")
print("-------------------------------------------------------")
print("Full Name: ", firstName, lastName)
print("Hourly Salary: %6.2f" % hSalary)
print("=======================================================")
print("Time Worked Summary")
print("--------+---------+-----------+----------+-------------")
print(" Monday | Tuesday | Wednesday | Thursday | Friday")
print("--------+---------+-----------+----------+-------------")
print(F"{mon:6.2f} | {tue:6.2f} | {wed:6.2f} | {thu:6.2f} |{fri:6.2f}")
print("========+=========+===========+==========+=============")
print(" Pay Summary")
print("-------------------------------------------------------")
print(" Time Pay")
print("-------------------------------------------------------")
print(F" Regular: {regTime:6.2f} {regPay:6.2f}")
print("-------------------------------------------------------")
print(f" overtime: {overtime:6.2f} {overPay:6.2f}")
print("=======================================================")
print(f" Net Pay: {netPay:6.2f}")
print("=======================================================")
into a match statement like this:
print("FUN DEPARTMENT STORE") print("=======================================================") print("Payroll Preparation") . . . match timeWorked <= 40.00: case True: regTime = timeWorked regPay = hSalary * timeWorked overtime = 0.00 overPay = 0.00 case False: regTime = 40.00 regPay = hSalary * 40.00 overtime = timeWorked - 40.00 overPay = hSalary * 1.50 * overtime . . .
Here is an example of running the program:
FUN DEPARTMENT STORE ======================================================= Payroll Preparation ------------------------------------------------------- Enter the following pieces of information ------------------------------------------------------- Employee Information ------------------------------------------------------- First Name: Annette Last Name: Burns Hourly Salary: 24.86 ------------------------------------------------------- Time worked ------------------------------------------------------- Monday: 8 Tuesday: 10 Wednesday: 8 Thursday: 9.5 Friday: 9 +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ FUN DEPARTMENT STORE ======================================================= Payroll Evaluation ======================================================= Employee Information ------------------------------------------------------- Full Name: Annette Burns Hourly Salary: 24.86 ======================================================= Time Worked Summary --------+---------+-----------+----------+------------- Monday | Tuesday | Wednesday | Thursday | Friday --------+---------+-----------+----------+------------- 8.00 | 10.00 | 8.00 | 9.50 | 9.00 ========+=========+===========+==========+============= Pay Summary ------------------------------------------------------- Time Pay ------------------------------------------------------- Regular: 40.00 994.40 ------------------------------------------------------- overtime: 4.50 167.81 ======================================================= Net Pay: 1162.20 ======================================================= Press any key to continue . . .
Nesting a Conditional Statement in a Case
Each case of a match statement has its own body. In that body, you write any code necessary for the outcome of that case. To process that outcome, you can create one or more conditional statements. This is the same as nesting one or more conditional statements, as we saw when studying conditional conjunctions and disjunctions.
Practical Learning: matching a String
print("==========================================") print(" - Amazing DeltaX - State Income Tax -") print("==========================================") stateName = "" taxRate = 0.00 amountAdded = 0.00 print("Enter the information for tax preparation") print("States") print(" AK - Alaska") print(" AR - Arkansas") print(" CO - Colorado") print(" FL - Florida") print(" GA - Georgia") print(" IL - Illinois") print(" IN - Indiana") print(" KY - Kentucky") print(" MA - Massachusetts") print(" MI - Michigan") print(" MO - Missouri") print(" MS - Mississippi") print(" NV - Nevada") print(" NH - New Hampshire") print(" NC - North Carolina") print(" PA - Pennsylvania") print(" SD - South Dakota") print(" TN - Tennessee") print(" TX - Texas") print(" UT - Utah") print(" WA - Washington") print(" WY - Wyoming") abbr = input("\nEnter State Abbreviation: "); print("--------------------------------------------") grossSalary = float(input("Gross Salary: ")) match abbr: case "CO": taxRate = 4.63 amountAdded = 0.00 stateName = "Colorado" case "FL": taxRate = 0.00 amountAdded = 0.00 stateName = "Florida" case "KY": taxRate = 5.00 amountAdded = 0.00 stateName = "Kentucky" case "IL": taxRate = 4.95 amountAdded = 0.00 stateName = "Illinois" case "IN": taxRate = 3.23 stateName = "Indiana" case "MA": taxRate = 5.00 amountAdded = 0.00 stateName = "Massachusetts" case "MI": taxRate = 4.25 amountAdded = 0.00 stateName = "Michigan" case "NC": taxRate = 5.25 amountAdded = 0.00 stateName = "North Carolina" case "NH": taxRate = 5.00 amountAdded = 0.00 stateName = "New Hampshire" case "NV": taxRate = 0.00 amountAdded = 0.00 stateName = "Nevada" case "PA": taxRate = 3.07 amountAdded = 0.00 stateName = "Pennsylvania" case "TN": taxRate = 1.00 amountAdded = 0.00 stateName = "Tennessee" case "TX": taxRate = 0.00 amountAdded = 0.00 stateName = "Texas" case "UT": taxRate = 4.95 amountAdded = 0.00 stateName = "Utah" case "WA": taxRate = 0.00 amountAdded = 0.00 stateName = "Washington" case "WY": taxRate = 0.00 amountAdded = 0.00 stateName = "Wyoming" case "MO": stateName = "Missouri" if (grossSalary >= 0.00) and (grossSalary <= 106): amountAdded = 0 taxRate = 0.00 elif (grossSalary > 106) and (grossSalary <= 1_073): amountAdded = 0 taxRate = 1.50 elif (grossSalary > 1_073) and (grossSalary <= 2_146): amountAdded = 16 taxRate = 2.00 elif (grossSalary > 2_146) and (grossSalary <= 3_219): amountAdded = 37 taxRate = 2.50 elif (grossSalary > 3_219) and (grossSalary <= 4_292): amountAdded = 64 taxRate = 3.00 elif (grossSalary > 4_292) and (grossSalary <= 5_365): amountAdded = 96 taxRate = 3.50 elif (grossSalary > 5_365) and (grossSalary <= 6_438): amountAdded = 134 taxRate = 4.00 elif (grossSalary > 6_438) and (grossSalary <= 7_511): amountAdded = 177; taxRate = 4.50; elif (grossSalary > 7_511) and (grossSalary <= 8_584): amountAdded = 225 taxRate = 5.00 else: # if(grossSalary > 8_584) amountAdded = 279 taxRate = 5.40 taxAmount = amountAdded + (grossSalary * taxRate / 100.00) netPay = grossSalary - taxAmount print("============================================") print(" - Amazing DeltaX - State Income Tax -") print("============================================") print(" %s" % stateName) print("--------------------------------------------") print(F"Gross Salary: {grossSalary:6.2f}") print(F"Tax Rate: {taxRate:7.2f}%") print("--------------------------------------------") print(F"Tax Amount: {taxAmount:7.2f}") print(F"Net Pay: {netPay:6.2f}") print("============================================")
========================================== - Amazing DeltaX - State Income Tax - ========================================== Enter the information for tax preparation States AK - Alaska AR - Arkansas CO - Colorado FL - Florida GA - Georgia IL - Illinois IN - Indiana KY - Kentucky MA - Massachusetts MI - Michigan MO - Missouri MS - Mississippi NV - Nevada NH - New Hampshire NC - North Carolina PA - Pennsylvania SD - South Dakota TN - Tennessee TX - Texas UT - Utah WA - Washington WY - Wyoming Enter State Abbreviation: MO -------------------------------------------- Gross Salary: 2688.75 ============================================ - Amazing DeltaX - State Income Tax - ============================================ Missouri -------------------------------------------- Gross Salary: 2688.75 Tax Rate: 2.50% -------------------------------------------- Tax Amount: 104.22 Net Pay: 2584.53 ============================================ Press any key to continue . . .
""" The Traffic Tickets System is a small (console/terminal-based) application that allows a fictitious government (in the United States) or to assist a fictitious police department to manage traffic tickets, tickets based on the types of roads, the types of signs posted on roads, the speed limits, the traffic lights, etc. This is an application for entertainment purposes only. Don't take any aspect of this application seriously. The Violation variable is used to identify the type of violation or infraction that was committed by a driver. """ violation = '' """ We will use the TypeOfIssue variable to address some concerns or situation(s) related to the person who is operating a vehicle. """ typeOfIssue = '' # Because every road has a speed limit, which is usually clearly posted # on the side of a road, our application wants to know the speed limit... drivingSpeed = 0 # ... and the speed at which the vehicle was proceeding. postedSpeedLimit = 0 """ The following two variables are used to set the amount of a ticket (remember that this application is just for entertainment purposes). """ baseTicket = 0.00 additionalFee = 0.00 # These variables will be used to display the summary of the ticket. strPeriod = '' strRoadType = "" strTypeOfIssue = "" strTypeOfViolation = "" print("Traffic Tickets System") print("==========================================================") """ Starting here, a police officer, a government clerk, or a designated user is used an application on a computer. We want the person to make selections on the application. We want to know the period during which the infraction was committed. """ print("Periods") print("1 - Monday-Friday - Night (7PM - 6AM)") print("2 - Monday-Friday - Morning Rush Hour (6AM - 9AM)") print("3 - Monday-Friday - Regular Time (9AM - 3PM)") print("4 - Monday-Friday - Afternoon Rush Hour (3PM - 7PM)") print("5 - Weekend (Saturday-Sunday) and Holidays") print("----------------------------------------------------------") period = int(input("Period of the infraction (1-5): ")) match period: case 1: strPeriod = "Monday-Friday - Night (7PM - 6AM)" case 2: strPeriod = "Monday-Friday - Morning Rush Hour (6AM - 9AM)" case 3: strPeriod = "Monday-Friday - Regular Time (9AM - 3PM)" case 4: strPeriod = "Monday-Friday - Afternoon Rush Hour (3PM - 7PM)" case 5: strPeriod = "Weekend (Saturday-Sunday) and Holidays" print("==========================================================") # We want to know the type or category of road where the violation was committed. print("Type of Road") # Interstate issues include slow driving, fast driving, aggressive driving, etc. print("1 - Interstate (Ex. I95)") """ Federal/State Highway include the characteristics of Interstate roads. Although many federal and state highways appear like interstate roads, some of those highways have traffic lights (green light, orange light, red light, flashing orange lights, flashing red lights). """ print("2 - Federal/State Highway (Ex. US50)") # State roads include the same issues as Federal/State Highway. Some State roads may have Stop signs. print("3 - State Road (Ex. TN22, MD410)") # County/Local roads include the same issues as State roads. Additionally, they have Stop signs. print("4 - County/Local Road (Ex. Randolph Rd, Eusebio Ave, Abena Blvd) or Local - Unknown (Ex. Sterling Str, Garvey Court)") print("----------------------------------------------------------") roadType = int(input("Type of road (1-4): ")) match roadType: case 1: strRoadType = "Interstate" case 2: strRoadType = "Federal/State Highway" case 3: strRoadType = "State Road" case 4: strRoadType = "County/Local Road, Others" print("==========================================================") # Let the user specify the speed limit on the road postedSpeedLimit = int(input("Posted Speed Limit: ")) # The application wants to know at what speed the vehicle was operated drivingSpeed = int(input("Driving Speed: ")) print("==========================================================") """ Everything considered, or no matter what, there are issues related either to the driver who is operating the vehicle, or issues related to the vehicles. We will mention some of those issues here. """ print("Types of issues") print("0 - No particular issues") print("1 - Health issues") print("2 - Driving while sleeping") print("3 - Driving while using an electronic device") print("4 - Driving under the influence (of alcohol, drugs, intoxicating products, etc)") typeOfIssue = int(input("\nType of issue (0-4): ")) if typeOfIssue == 1: """ The driver was found with a health related issue. Try to assist the driver who is probably having an issue. If the driver is having a health issue: 1. Ask to park the car on the road shoulder if possible 2. Get an "In case of emergency" number from the driver and call a family member, friend, etc 3. Call an ambulance to take the driver to an Emergency Room 4. Don't issue a ticket """ baseTicket = 0.00 strTypeOfIssue = "Health issues" elif typeOfIssue == 2: """ If the driver is sleeping while driving: 1. If the driver is having a health issue, proceed as in the previous section. If not, take the driver into custody 2. Impound the vehicle 3. Issue a ticket: $100 """ baseTicket = 150.00 strTypeOfIssue = "Driving while sleeping" elif typeOfIssue == 3: """ If the driver is using an electronic device (cellphone, etc) while driving: 1. Stop the driver 2. Issue a ticket: $150 (and let the driver go) """ baseTicket = 100.00 strTypeOfIssue = "Driving while using an electronic device" elif typeOfIssue == 4: """ If the driver is operating the vehicle while intoxicated: 1. Stop the vehicle. Find out whether it is a legitimate medical/health issue. If that's the case, do as in the first case. If not: 2. Impound the vehicle 3. (Normally, or in reality, the driver must appear in court where a traffic judge will make all the decisions; but for the sake of our simple application, ...) Issue a ticket: $350 """ baseTicket = 350.00 strTypeOfIssue = "Driving under the influence (alcohol, drugs, intoxicating products, or else)" else: # if typeOfIssue == 0: baseTicket = 0.00 strTypeOfIssue = "No particular issues relatted to the traffic violation" print("==========================================================") """ For our entertainment-based application, the amount of ticket will depend on the type of road where the violation took place. """ if roadType == 1: # Interstate print("Type of Traffic Violation") print("1 - Slow Driving") print("2 - Fast Driving") print("3 - Aggressive Driving") print("4 - Unknown - Other") print("----------------------------------------------------------") violation = int(input("Type of violaction (1-4): ")) match violation: case 1: additionalFee = 0.00 strTypeOfViolation = "Slow Driving" case 2: additionalFee = 100.00 strTypeOfViolation = "Fast Driving" case 3: additionalFee = 125.00 strTypeOfViolation = "Aggressive Driving" case 4: additionalFee = 50.00 strTypeOfViolation = "Unknown - Other" elif roadType == 2: print("Type of Traffic Violation") print("1 - Slow Driving") print("2 - Fast Driving") print("3 - Aggressive Driving") print("4 - Driving Through Steady Red Light") print("5 - Driving Through Flashing Red Light") print("6 - Red Light Right Turn Without Stopping") print("7 - Unknown - Other") print("----------------------------------------------------------") violation = int(input("Type of violaction (1-7): ")); match violation: case 1: additionalFee = 0.00 strTypeOfViolation = "Slow Driving" case 2: additionalFee = 65.00 strTypeOfViolation = "Fast Driving" case 3: additionalFee = 75.00 strTypeOfViolation = "Aggressive Driving" case 4: additionalFee = 105.00 strTypeOfViolation = "Driving Through Steady Red Light" case 5: additionalFee = 35.00 strTypeOfViolation = "Driving Through Flashing Red Light" case 6: additionalFee = 25.00 strTypeOfViolation = "Red Light Right Turn Without Stopping" case 8: additionalFee = 5.00 strTypeOfViolation = "Unknown - Other" else: print("Type of Traffic Violation") print("1 - Slow Driving") print("2 - Fast Driving") print("3 - Aggressive Driving") print("4 - Driving Through Steady Red Light") print("5 - Driving Through Flashing Red Light") print("6 - Red Light Right Turn Without Stopping") print("7 - Driving Through Stop Sign Without Stopping") print("8 - Unknown - Other") print("----------------------------------------------------------") violation = int(input("Type of violaction (1-8): ")); match violation: case 1: additionalFee = 0.00 strTypeOfViolation = "Slow Driving" case 2: additionalFee = 35.00 strTypeOfViolation = "Fast Driving" case 3: additionalFee = 55.00 strTypeOfViolation = "Aggressive Driving" case 4: additionalFee = 65.00 strTypeOfViolation = "Driving Through Steady Red Light" case 5: additionalFee = 55.00 strTypeOfViolation = "Driving Through Flashing Red Light" case 6: additionalFee = 35.00 strTypeOfViolation = "Red Light Right Turn Without Stopping" case 7: additionalFee = 15.00 strTypeOfViolation = "Driving Through Stop Sign Without Stopping" case 8: additionalFee = 5.00 strTypeOfViolation = "Unknown - Other" print("==========================================================") print("Traffic Ticket Summary") print("----------------------------------------------------------") print("Period of the day: %s" % strPeriod) print("Road Type: %s" % strRoadType) print("Posted Speed Limit: %s" % postedSpeedLimit) print("Driving Speed: %s" % drivingSpeed) print("Type of Issue: %s" % strTypeOfIssue) print(" Base Ticket: %i" % baseTicket) print("Violation Type: %s" % strTypeOfViolation) print(" Addition Fee: %i" % additionalFee) print("----------------------------------------------------------") print("Ticket Amount: %i" % (baseTicket + additionalFee)); print("==========================================================")
Periods: 1 Type of Road: 1 Posted Speed Limit: 60 Driving Speed: 120 Type of Issue: 3 --------------------------------- Traffic Tickets System ========================================================== Periods 1 - Monday-Friday - Night (7PM - 6AM) 2 - Monday-Friday - Morning Rush Hour (6AM - 9AM) 3 - Monday-Friday - Regular Time (9AM - 3PM) 4 - Monday-Friday - Afternoon Rush Hour (3PM - 7PM) 5 - Weekend (Saturday-Sunday) and Holidays ---------------------------------------------------------- Period of the infraction (1-5): 1 ========================================================== Type of Road 1 - Interstate (Ex. I95) 2 - Federal/State Highway (Ex. US50) 3 - State Road (Ex. TN22, MD410) 4 - County/Local Road (Ex. Randolph Rd, Eusebio Ave, Abena Blvd) or Local - Unknown (Ex. Sterling Str, Garvey Court) ---------------------------------------------------------- Type of road (1-4): 1 ========================================================== Posted Speed Limit: 60 Driving Speed: 120 ========================================================== Types of issues 0 - No particular issues 1 - Health issues 2 - Driving while sleeping 3 - Driving while using an electronic device 4 - Driving under the influence (of alcohol, drugs, intoxicating products, etc) Type of issue (0-4): 3 ========================================================== Type of Traffic Violation 1 - Slow Driving 2 - Fast Driving 3 - Aggressive Driving 4 - Unknown - Other ---------------------------------------------------------- Type of violaction (1-4): 3 ========================================================== Traffic Ticket Summary ---------------------------------------------------------- Period of the day: Monday-Friday - Night (7PM - 6AM) Road Type: Interstate Posted Speed Limit: 60 Driving Speed: 120 Type of Issue: Driving while using an electronic device Base Ticket: 100 Violation Type: Aggressive Driving Addition Fee: 125 ---------------------------------------------------------- Ticket Amount: 225 ========================================================== Press any key to continue . . .
Pattern Matching and Functions
We have already learned that one way to organize your code is to create functions or methods that each solves a particular problem. One way to make those functions or methods effective is to make them return a value that depends on some conditions. We learned to use if...else conditional statements to perform some validations. The match statement provides even more controls and options.
In a function, you can create a conditional match statement, get a value in each case, assign that value to a variable, and then return that value. Here is an example:
def IdentifyPeriodofDay(): strPeriod = '' print("Periods") print("1 - Monday-Friday - Night (7PM - 6AM)") print("2 - Monday-Friday - Morning Rush Hour (6AM - 9AM)") print("3 - Monday-Friday - Regular Time (9AM - 3PM)") print("4 - Monday-Friday - Afternoon Rush Hour (3PM - 7PM)") print("5 - Weekend (Saturday-Sunday) and Holidays") print("------------------------------------------------------------------") period = int(input("Period of the infraction (1-5): ")) match period: case 1: strPeriod = "Monday-Friday - Night (7PM - 6AM)" case 2: strPeriod = "Monday-Friday - Morning Rush Hour (6AM - 9AM)" case 4: strPeriod = "Monday-Friday - Afternoon Rush Hour (3PM - 7PM)" case 5: strPeriod = "Weekend (Saturday-Sunday) and Holidays" case 6: strPeriod = "Monday-Friday - Regular Time (9AM - 3PM)" return strPeriod print("==================================================================") print("Traffic Tickets System") print("==================================================================") per = IdentifyPeriodofDay() print("------------------------------------------------------------------") print("Period of the day: %s" % per) print("==================================================================")
Here is an example of running the program:
============================================================= Traffic Tickets System ============================================================= Periods 1 - Monday-Friday - Night (7PM - 6AM) 2 - Monday-Friday - Morning Rush Hour (6AM - 9AM) 3 - Monday-Friday - Regular Time (9AM - 3PM) 4 - Monday-Friday - Afternoon Rush Hour (3PM - 7PM) 5 - Weekend (Saturday-Sunday) and Holidays ---------------------------------------------------------- Period of the infraction (1-5): 2 ------------------------------------------------------------- Period of the day: Monday-Friday - Morning Rush Hour (6AM - 9AM) ============================================================= Press any key to continue . . .
Practical Learning: Processing a Matching Return
def IdentifyPeriodofDay(): print("Periods") print("1 - Monday-Friday - Night (7PM - 6AM)") print("2 - Monday-Friday - Morning Rush Hour (6AM - 9AM)") print("3 - Monday-Friday - Regular Time (9AM - 3PM)") print("4 - Monday-Friday - Afternoon Rush Hour (3PM - 7PM)") print("5 - Weekend (Saturday-Sunday) and Holidays") print("-----------------------------------------------------------------------") period = int(input("Period of the infraction (1-5): ")) match period: case 1: return "Monday-Friday - Night (7PM - 6AM)" case 2: return "Monday-Friday - Morning Rush Hour (6AM - 9AM)" case 3: return "Monday-Friday - Regular Time (9AM - 3PM)" case 4: return "Monday-Friday - Afternoon Rush Hour (3PM - 7PM)" case 5: return "Weekend (Saturday-Sunday) and Holidays" """ Starting here, a police officer, a government clerk, or a designated user is used an application on a computer. We want the person to make selections on the application. We want to know the period during which the infraction was committed. """ strPeriod = IdentifyPeriodofDay() print("=======================================================================") print("Traffic Tickets System") print("-----------------------------------------------------------------------") print("Period of Infraction: ", strPeriod) print("=======================================================================")
Periods 1 - Monday-Friday - Night (7PM - 6AM) 2 - Monday-Friday - Morning Rush Hour (6AM - 9AM) 3 - Monday-Friday - Regular Time (9AM - 3PM) 4 - Monday-Friday - Afternoon Rush Hour (3PM - 7PM) 5 - Weekend (Saturday-Sunday) and Holidays ----------------------------------------------------------------------- Period of the infraction (1-5): 4 ======================================================================= Traffic Tickets System ----------------------------------------------------------------------- Period of Infraction: Monday-Friday - Afternoon Rush Hour (3PM - 7PM) ======================================================================= Press any key to continue . . .
Matching a Selection in a Property Reader
Besides an if condition, you can use a statement, you can use a match statement to select some values that may match a condition.
match():
As mentioned above, you start with the match() statement that is followed by a body delimited by curly brackets. In the parentheses of match(), you can put the name of a variable. That variable must already exist and must hold a valid value. As we will see in later sections. The value in the parentheses of match() can also be an expression that can be evaluated to a valid value. The body of the match statement contains one or more sections that each starts with the case keyword. Each case section uses a body from a colon to a break; line. In that body, you will write code to process the outcome of that case or selection.
The match statement accepts different types of expressions or values.
Practical Learning: Introducing Condition Statements in Properties
namespace TaxPreparation10 { public class IncomeTax { private string abrv; private string _nm_; private double grsSal; public string Abbreviation { get { return abrv; } set { abrv = value; } } public string StateName { get { match (abrv) { case "CO": _nm_ = "Colorado" case "FL": _nm_ = "Florida" case "KY": _nm_ = "Kentucky" case "IL": _nm_ = "Illinois" case "IN": _nm_ = "Indiana" case "MA": _nm_ = "Massachusetts" case "MI": _nm_ = "Michigan" case "NC": _nm_ = "North Carolina" case "NH": _nm_ = "New Hampshire" case "NV": _nm_ = "Nevada" case "PA": _nm_ = "Pennsylvania" case "TN": _nm_ = "Tennessee" case "TX": _nm_ = "Texas" case "UT": _nm_ = "Utah" case "WA": _nm_ = "Washington" case "WY": _nm_ = "Wyoming" case "MO": _nm_ = "Missouri" case "MT": _nm_ = "Montana" } return _nm_; } } public double GrossSalary { set { grsSal = value; } get { return grsSal; } } public double TaxAmount { get { double amt = 0.00 match(abrv) { case "CO": amt = GrossSalary * 4.63 / 100; case "FL": case "NV": case "TX": case "WA": case "WY": amt = 0.00 case "KY": case "MA": case "NH": amt = GrossSalary * 5.00 / 100; case "IL": case "UT": amt = GrossSalary * 4.95 / 100; case "IN": amt = GrossSalary * 3.23 / 100; case "MI": amt = GrossSalary * 4.25 / 100; case "NC": amt = GrossSalary * 5.25 / 100; case "PA": amt = GrossSalary * 3.07 / 100; case "TN": amt = GrossSalary * 1.00 / 100; case "MO": # Missouri if ((GrossSalary >= 0.00) && (GrossSalary <= 106)) { amt = 0.00 } elif ((GrossSalary > 106) && (GrossSalary <= 1_073)) { amt = GrossSalary * 1.50 / 100; } elif ((GrossSalary > 1_073) && (GrossSalary <= 2_146)) { amt = 16 + (GrossSalary * 2.00 / 100); } elif ((GrossSalary > 2_146) && (GrossSalary <= 3_219)) { amt = 37 + (GrossSalary * 2.50 / 100); } elif ((GrossSalary > 3_219) && (GrossSalary <= 4_292)) { amt = 64 + (GrossSalary * 3.00 / 100); } elif ((GrossSalary > 4_292) && (GrossSalary <= 5_365)) { amt = 96 + (GrossSalary * 3.50 / 100); } elif ((GrossSalary > 5_365) && (GrossSalary <= 6_438)) { amt = 134 + (GrossSalary * 4.00 / 100); } elif ((GrossSalary > 6_438) && (GrossSalary <= 7_511)) { amt = 177 + (GrossSalary * 4.50 / 100); } elif ((GrossSalary > 7_511) && (GrossSalary <= 8_584)) { amt = 225 + (GrossSalary * 5.00 / 100); } else # if(GrossSalary > 8_584) { amt = 279 + (GrossSalary * 5.40 / 100); } case "MT": """ Montana * https://montana.servicenowservices.com/citizen/kb?id=kb_article_view&sysparm_article=KB0014487 * 2020 Individual Income Tax Rates * If your taxable income is more than but not more than Your tax is minus * $0 $3,100 1% of your taxable income $0 * $3,100 $5,500 2% of your taxable income $31 * $5,500 $8,400 3% of your taxable income $86 * $8,400 $11,300 4% of your taxable income $170 * $11,300 $14,500 5% of your taxable income $283 * $14,500 $18,700 6% of your taxable income $428 * $18,700 6.9% of your taxable income $596 */ if (GrossSalary >= 0.00) && (GrossSalary <= 3_100): amt = (GrossSalary * 1 / 100) elif (GrossSalary > 3_100) && (GrossSalary <= 5_500): amt = (GrossSalary * 2 / 100) - 31 elif (GrossSalary > 5_500) && (GrossSalary <= 8_400): amt = (GrossSalary * 3 / 100) - 86 elif (GrossSalary > 8_400) && (GrossSalary <= 11_300): amt = (GrossSalary * 4 / 100) - 170 elif (GrossSalary > 11_300) && (GrossSalary <= 14_500): amt = (GrossSalary * 5 / 100) - 283 elif (GrossSalary > 14_500) && (GrossSalary <= 18_700): amt = (GrossSalary * 6 / 100) - 428 else: # if grossSalary > 18_700: amt = (GrossSalary * 6.90 / 100) - 596 return amt } public double NetPay { get { return grsSal - TaxAmount; } } } }
using TaxPreparation10; IncomeTax tax = new IncomeTax(); print("==========================================") print(" - Amazing DeltaX - State Income Tax -") print("==========================================") print("Enter the information for tax preparation") print("States") print(" AK - Alaska") print(" AR - Arkansas") print(" CO - Colorado") print(" FL - Florida") print(" GA - Georgia") print(" IL - Illinois") print(" IN - Indiana") print(" KY - Kentucky") print(" MA - Massachusetts") print(" MI - Michigan") print(" MO - Missouri") print(" MS - Mississippi") print(" NV - Nevada") print(" NH - New Hampshire") print(" NC - North Carolina") print(" PA - Pennsylvania") print(" SD - South Dakota") print(" TN - Tennessee") print(" TX - Texas") print(" UT - Utah") print(" WA - Washington") print(" WY - Wyoming") print("Enter State Abbreviation: ") tax.Abbreviation = input(); print("--------------------------------------------") tax.GrossSalary = float(input("Gross Salary: ")) print("============================================") print(" - Amazing DeltaX - State Income Tax -") print("--------------------------------------------") print(" {tax.StateName}") print("Gross Salary: {tax.GrossSalary:6.2f}") print("--------------------------------------------") print("Tax Amount: {tax.TaxAmount:6.2f}") print("Net Pay: {tax.NetPay:6.2f}") print("============================================")
========================================== - Amazing DeltaX - State Income Tax - ========================================== Enter the information for tax preparation States AK - Alaska AR - Arkansas CO - Colorado FL - Florida GA - Georgia IL - Illinois IN - Indiana KY - Kentucky MA - Massachusetts MI - Michigan MO - Missouri MS - Mississippi NV - Nevada NH - New Hampshire NC - North Carolina PA - Pennsylvania SD - South Dakota TN - Tennessee TX - Texas UT - Utah WA - Washington WY - Wyoming Enter State Abbreviation: FL -------------------------------------------- Gross Salary: 6248.85 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- Florida Gross Salary: 6248.85 -------------------------------------------- Tax Amount: 0.00 Net Pay: 6248.85 ============================================ Press any key to continue . . .
========================================== - Amazing DeltaX - State Income Tax - ========================================== Enter the information for tax preparation States AK - Alaska AR - Arkansas CO - Colorado FL - Florida GA - Georgia IL - Illinois IN - Indiana KY - Kentucky MA - Massachusetts MI - Michigan MO - Missouri MS - Mississippi NV - Nevada NH - New Hampshire NC - North Carolina PA - Pennsylvania SD - South Dakota TN - Tennessee TX - Texas UT - Utah WA - Washington WY - Wyoming Enter State Abbreviation: NC -------------------------------------------- Gross Salary: 6248.85 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- North Carolina Gross Salary: 6248.85 -------------------------------------------- Tax Amount: 328.06 Net Pay: 5920.79 ============================================ Press any key to continue . . .
========================================== - Amazing DeltaX - State Income Tax - ========================================== Enter the information for tax preparation States AK - Alaska AR - Arkansas CO - Colorado FL - Florida GA - Georgia IL - Illinois IN - Indiana KY - Kentucky MA - Massachusetts MI - Michigan MO - Missouri MS - Mississippi NV - Nevada NH - New Hampshire NC - North Carolina PA - Pennsylvania SD - South Dakota TN - Tennessee TX - Texas UT - Utah WA - Washington WY - Wyoming Enter State Abbreviation: MO -------------------------------------------- Gross Salary: 6248.85 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- Missouri Gross Salary: 6248.85 -------------------------------------------- Tax Amount: 383.95 Net Pay: 5864.90 ============================================ Press any key to continue . . .
========================================== - Amazing DeltaX - State Income Tax - ========================================== Enter the information for tax preparation States AK - Alaska AR - Arkansas CO - Colorado FL - Florida GA - Georgia IL - Illinois IN - Indiana KY - Kentucky MA - Massachusetts MI - Michigan MO - Missouri MS - Mississippi NV - Nevada NH - New Hampshire NC - North Carolina PA - Pennsylvania SD - South Dakota TN - Tennessee TX - Texas UT - Utah WA - Washington WY - Wyoming Enter State Abbreviation: MT -------------------------------------------- Gross Salary: 6248.85 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- Montana Gross Salary: 6248.85 -------------------------------------------- Tax Amount: 101.47 Net Pay: 6147.38 ============================================ Press any key to continue . . .
Matching a Tuple
Considering a Tuple for Each Case
Since an item of a tuple primarily holds a value, you can use it in a matching conditional statement. Here is an example:
(int memNbr, string name, string category, int fee) member;
member.memNbr = 297_624;
member.name = "Catherine Simms"
member.category = "Senior"
member.fee = -1;
match member.category:
case "Yound Adult":
member.fee = 15
case "Adult":
member.fee = 45
case "Senior":
member.fee = 25
default:
member.fee = 0
print("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=")
print("Club Membership")
print("==============================================")
print("Member Information")
print("----------------------------------------------")
print("Membership #: {member.memNbr}")
print("Member Name: {member.name}")
print("Membership Type: {member.category}")
print("----------------------------------------------")
print("Membership Fee: {member.fee}")
print("==============================================")
This would produce:
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= Club Membership ============================================== Member Information ---------------------------------------------- Membership #: 297624 Member Name: Catherine Simms Membership Type: Senior ---------------------------------------------- Membership Fee: 25 ============================================== Press any key to continue . . .
In reality, because a tuple is some kind of a variable, you can use it as the values to consider in a match statement. To start, pass the name of the tuple to the parentheses of match(). Then for each case, provide a complete set of values in parentheses about the tuple. You can then process different cases normally. Here is an example:
(int number, string name, bool allowedFullTime) member; print("Enter the values about the employee") print("-----------------------------------------------------------------------") print("Employee #: ") member.number = int(input)); print("Employee Name: ") member.name = input(); print("Is the employee allowed to work full-time (y/n): ") answer = input(); match (answer) { case "y" or "Y": member.allowedFullTime = true; default: member.allowedFullTime = false; } print("=======================================================================") print("Fun Department Store") print("Employee Record") print("-----------------------------------------------------------------------") print("Employee #: {member.number}") print("Employee Name: {member.name}") print("Full-Time? {member.allowedFullTime}") print("-----------------------------------------------------------------------") match(member) { case (975_947, "Alex Miller", false): print("The employee is not allowed to work overtime.") case (283_570, "Juliana Schwartz", true): print("This is a full-time employee who is allowed to work overtime.") case (283_624, "Arturo Garcia", true): print("This iemployee can work full-time.") default: print("The employee is not properly identified.") } print("=======================================================================")
Here is an example of running the program:
Enter the values about the employee ----------------------------------------------------------------------- Employee #: 608624 Employee Name: Arturo Garcia Is the employee allowed to work full-time (y/n): Y ======================================================================= Fun Department Store Employee Record ----------------------------------------------------------------------- Employee #: 608624 Employee Name: Arturo Garcia Full-Time? True ----------------------------------------------------------------------- This employee can work full-time. ======================================================================= Press any key to continue . . .
Here is another example of running the program:
Enter the values about the employee ----------------------------------------------------------------------- Employee #: 975947 Employee Name: Alex Miller Is the employee allowed to work full-time (y/n): N ======================================================================= Fun Department Store Employee Record ----------------------------------------------------------------------- Employee #: 975947 Employee Name: Alex Miller Full-Time? False ----------------------------------------------------------------------- The employee is not allowed to work overtime. ======================================================================= Press any key to continue . . .
Here is one more example of running the program:
Enter the values about the employee ----------------------------------------------------------------------- Employee #: 608624 Employee Name: Jules Garcia Is the employee allowed to work full-time (y/n): Not sure ======================================================================= Fun Department Store Employee Record ----------------------------------------------------------------------- Employee #: 608624 Employee Name: Jules Garcia Full-Time? False ----------------------------------------------------------------------- The employee is not properly identified. ======================================================================= Press any key to continue . . .
Returning a Tuple
We already know that one way to make a function or method produce many values is to make it return a tuple. Based on this, you can create a function that includes a match statement that returns a value based on a condition that itself produces a tuple. Here is an example:
int GetViolation()
{
print("Type of Traffic Violation")
print("1 - Slow Driving")
print("2 - Fast Driving")
print("3 - Aggressive Driving")
print("4 - Unknown - Other")
print("--------------------------------------")
print("Type of violaction (1-4): ")
return int(input));
}
(int abc, string xyz) Evaluate(int problem)
{
(int a, string b) result;
match (problem)
{
case 1:
result = (0, "Slow Driving")
case 2:
result = (100, "Fast Driving")
case 3:
result = (125, "Aggressive Driving")
default:
result = (50, "Unknown - Other")
}
return result;
}
int infraction = GetViolation();
(int amount, string message) ticket = Evaluate(infraction);
print("Ticket Summary")
print("======================================")
print("Traffic Violation: %s" % ticket.message);
print("Ticket Amount: %s" % ticket.amount);
As seen with primitive values, instead of using a local tuple variable and assigning a value to it in each case, you can return the necessary value in each case clause. Here is an example:
(int abc, string xyz) Evaluate(int problem) { match (problem) { case 1: return (0, "Slow Driving") case 2: return (100, "Fast Driving") case 3: return (125, "Aggressive Driving") default: return (50, "Unknown - Other") } }
Practical Learning: Ending the Lesson
|
|||
Previous | Copyright © 2001-2024, FunctionX | Thursday 25 July 2024, 15:12 | Home |
|