
Concept explainers
Validation of date input
Program plan:
- Define the “leap_Year()” function,
- Check whether the year is not divisible by "4",
- If the condition is “True”, return “False”.
- Otherwise, check whether the year is divisible by "100",
- If it is “True”, check whether the year is divisible by "400",
- If it is “True”, return “True”.
- Otherwise, return “False”.
- Otherwise, return “True”.
- If it is “True”, check whether the year is divisible by "400",
- Check whether the year is not divisible by "4",
- Define the “main()” function,
- Execute the “try” statement to raise the exception if it is occurred.
- Get the input from the user.
- Split the user input based on "/" using “split()”.
- Convert the string type inputs into integer type.
- Check whether either the month is greater than “12” or day is greater than “12”,
- If it is “True”, print the string “This date is invalid”
- Otherwise, check whether the day is less than or equal to “28”,
- If it is “True”, print the string as “This date is valid”.
- Otherwise, check whether the month is "2" and "29",
-
- If it is “True”, check whether the Boolean value return from “leap_Year()” is “False”.
- If it is “True”, print “This date is invalid”.
- Otherwise, print “This date is valid”.
- Otherwise, check whether the day is “31”,
- If it “True”, check whether the month is either "2" or "4" or "6" or "11",
- If the above condition is “True”, print invalid.
- Otherwise, print valid.
- Otherwise, print “This date is valid”.
- If it is “True”, check whether the Boolean value return from “leap_Year()” is “False”.
- Catch the exception using “except ValueError” statement, if the exception of type “ValueError” occurs.
- Handle the exception.
- Catch the exception using “except” statement, if any type of exception occurs.
- Call the function “main()”.
- Execute the “try” statement to raise the exception if it is occurred.

This Python program is to add decisions and exception handling as required making it truly robust.
Explanation of Solution
Program:
File name: “year.py”
#Define the function
def leap_Year(yr):
#Check whether the year is not divisible by "4"
if (yr % 4) != 0:
#Return the boolean value
return False
#Otherwise
else:
#Check whether the year is divisible by "100"
if (yr % 100) == 0:
#Check whether the year is divisible by "400"
if (yr % 400) ==0:
#Return boolean value
return True
#Otherwise
else:
#Return boolean value
return False
#Otherwise
else:
#Return boolean value
return True
#Define the function
def main():
#Make a try
try:
#Get the input from the user
date_Str = input("Enter a date in the form MM/DD/YYYY: ")
#Split the user input based on "/" using split()
month_Str, day_Str, year_Str = date_Str.split("/")
#Convert the string into integer
mon = int(month_Str)
#Convert the string into integer
d = int(day_Str)
#Convert the string into integer
yr = int(year_Str)
#Execute the condition
if mon > 12 or d > 31:
#Print the string
print("This date is invalid.")
#Otherwise
else:
#Check whether the day is less than or equal to 28
if d <= 28:
#Print the string
print("This date is valid.")
#Check whether the month is "2" and "29"
elif mon == 2 and d == 29:
#Check whether the boolean value return from "leap_Year()" is "False"
if leap_Year(yr) == False:
#Print the string
print("This date is invalid.")
#Otherwise
else:
#Print the string
print("This date is valid.")
#Check whether the day is "31"
elif d == 31:
'''Check whether the month is either "2" or "4" or "6" or "11"'''
if mon == 2 or 4 or 6 or 11:
#Print the string
print("This date is invalid")
#Otherwise
else:
#Print the string
print("This date is valid")
#Otherwise
else:
#Print the string
print("The date is valid.")
#Catch the exception
except ValueError:
#Handle the exception
print("Your input was not in the correct form.")
#Catch the exception
except:
#Handle the exception
print("Something went wrong!")
#Call the function
main()
Output:
Enter a date in the form MM/DD/YYYY: 02/30/2000
The date is valid.
>>>
Additional output:
Enter a date in the form MM/DD/YYYY: 02-05-2000
Your input was not in the correct form.
>>>
Additional output:
Enter a date in the form MM/DD/YYYY: 06/31/2000
This date is invalid
>>>
Want to see more full solutions like this?
Chapter 7 Solutions
Python Programming: An Introduction to Computer Science, 3rd Ed.
- This week we will be building a regression model conceptually for our discussion assignment. Consider your current workplace (or previous/future workplace if not currently working) and answer the following set of questions. Expand where needed to help others understand your thinking: What is the most important factor (variable) that needs to be predicted accurately at work? Why? Justify its selection as your dependent variable.arrow_forwardAccording to best practices, you should always make a copy of a config file and add a date to filename before editing? Explain why this should be done and what could be the pitfalls of not doing it.arrow_forwardIn completing this report, you may be required to rely heavily on principles relevant, for example, the Work System, Managerial and Functional Levels, Information and International Systems, and Security. apply Problem Solving Techniques (Think Outside The Box) when completing. should reflect relevance, clarity, and organisation based on research. Your research must be demonstrated by Details from the scenario to support your analysis, Theories from your readings, Three or more scholarly references are required from books, UWIlinc, etc, in-text or narrated citations of at least four (4) references. “Implementation of an Integrated Inventory Management System at Green Fields Manufacturing” Green Fields Manufacturing is a mid-sized company specialising in eco-friendly home and garden products. In recent years, growing demand has exposed the limitations of their fragmented processes and outdated systems. Different departments manage production schedules, raw material requirements, and…arrow_forward
- 1. Create a Book record that implements the Comparable interface, comparing the Book objects by year - title: String > - author: String - year: int Book + compareTo(other Book: Book): int + toString(): String Submit your source code on Canvas (Copy your code to text box or upload.java file) > Comparable 2. Create a main method in Book record. 1) In the main method, create an array of 2 objects of Book with your choice of title, author, and year. 2) Sort the array by year 3) Print the object. Override the toString in Book to match the example output: @Javadoc Declaration Console X Properties Book [Java Application] /Users/kuan/.p2/pool/plugins/org.eclipse.justj.openjdk.hotspo [Book: year=1901, Book: year=2010]arrow_forwardQ5-The efficiency of a 200 KVA, single phase transformer is 98% when operating at full load 0.8 lagging p.f. the iron losses in the transformer is 2000 watt. Calculate the i) Full load copper losses ii) half load copper losses and efficiency at half load. Ans: 1265.306 watt, 97.186%arrow_forward2. Consider the following pseudocode for partition: function partition (A,L,R) pivotkey = A [R] t = L for i L to R-1 inclusive: if A[i] A[i] t = t + 1 end if end for A [t] A[R] return t end function Suppose we call partition (A,0,5) on A=[10,1,9,2,8,5]. Show the state of the list at the indicated instances. Initial A After i=0 ends After 1 ends After i 2 ends After i = 3 ends After i = 4 ends After final swap 10 19 285 [12 pts]arrow_forward
- .NET Interactive Solving Sudoku using Grover's Algorithm We will now solve a simple problem using Grover's algorithm, for which we do not necessarily know the solution beforehand. Our problem is a 2x2 binary sudoku, which in our case has two simple rules: •No column may contain the same value twice •No row may contain the same value twice If we assign each square in our sudoku to a variable like so: 1 V V₁ V3 V2 we want our circuit to output a solution to this sudoku. Note that, while this approach of using Grover's algorithm to solve this problem is not practical (you can probably find the solution in your head!), the purpose of this example is to demonstrate the conversion of classical decision problems into oracles for Grover's algorithm. Turning the Problem into a Circuit We want to create an oracle that will help us solve this problem, and we will start by creating a circuit that identifies a correct solution, we simply need to create a classical function on a quantum circuit that…arrow_forwardusing r languagearrow_forward8. Cash RegisterThis exercise assumes you have created the RetailItem class for Programming Exercise 5. Create a CashRegister class that can be used with the RetailItem class. The CashRegister class should be able to internally keep a list of RetailItem objects. The class should have the following methods: A method named purchase_item that accepts a RetailItem object as an argument. Each time the purchase_item method is called, the RetailItem object that is passed as an argument should be added to the list. A method named get_total that returns the total price of all the RetailItem objects stored in the CashRegister object’s internal list. A method named show_items that displays data about the RetailItem objects stored in the CashRegister object’s internal list. A method named clear that should clear the CashRegister object’s internal list. Demonstrate the CashRegister class in a program that allows the user to select several items for purchase. When the user is ready to check out, the…arrow_forward
- 5. RetailItem ClassWrite a class named RetailItem that holds data about an item in a retail store. The class should store the following data in attributes: item description, units in inventory, and price. Once you have written the class, write a program that creates three RetailItem objects and stores the following data in them: Description Units in Inventory PriceItem #1 Jacket 12 59.95Item #2 Designer Jeans 40 34.95Item #3 Shirt 20 24.95arrow_forwardFind the Error: class Information: def __init__(self, name, address, age, phone_number): self.__name = name self.__address = address self.__age = age self.__phone_number = phone_number def main(): my_info = Information('John Doe','111 My Street', \ '555-555-1281')arrow_forwardFind the Error: class Pet def __init__(self, name, animal_type, age) self.__name = name; self.__animal_type = animal_type self.__age = age def set_name(self, name) self.__name = name def set_animal_type(self, animal_type) self.__animal_type = animal_typearrow_forward
- Programming Logic & Design ComprehensiveComputer ScienceISBN:9781337669405Author:FARRELLPublisher:CengageC++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage LearningEBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENT
- Microsoft Visual C#Computer ScienceISBN:9781337102100Author:Joyce, Farrell.Publisher:Cengage Learning,C++ for Engineers and ScientistsComputer ScienceISBN:9781133187844Author:Bronson, Gary J.Publisher:Course Technology Ptr



