The following modules will be used to validate user input:
isblank_mod.py. This module ensures that the user does not leave any input for the required value blank.
age_mod.py. This module ensures that the user enters a valid date of birth, which includes a valid calendar month, day, and year. It also calculates the age based on the date of birth.
qty_mod.py. This module ensures that the quantity ordered is a numerical value and is a whole number.
creditcard.py. This module ensures that all the digits in the credit card num- ber are numeric and that it is a 16-digit number.
main_mod.py. This module does not perform any validation but imports other modules and calls functions from them.
Write the Code
Let’s now write the code.
The code for isblank_mod.py is as follows:
#isblank_mod.py def isblank(var):
#Function checks if the value passed in var is blank if len(var)==0:
print ‘You can\’t leave it blank’ else:
return 1
The code for age_mod.py is as follows:
import time
#Determines the current time in a list t=time.localtime(time.time())
#Extract the current year from the list cur_year=t[0]
cur_month=t[1] cur_day=t[2]
#Checks if the date of birth is valid def dobvalid_func(month,day,year):
while 1:
if year<=0 or month<=0 or day<=0: break
#Checks if current year is less than year of birth if cur_year<year:
break
if cur_year==year and cur_month>month: break
#Checks if month of birth is greater than 12 if month>12:
break
#Checks if number of days are
#greater than 31 for applicable month if month in (1,3,5,7,8,10,12):
if day>31: break
#Checks if number of days in date of birth #are greater than 30 for applicable month elif month in (4,6,9,11):
if day>30: break
#Checks if in a leap year, number of days #in date of birth are greater than 29 #for february
if year%4==0 and month==2: if day>29:
return 1 return 0
def age_cal(dob): if len(dob)<>10:
print “Date not in correct format!!” return 0
m=int(dob[:2]) #Extract month from date of birth d=int(dob[3:5]) #Extract day from date of birth y=int(dob[6:10]) #Extract year from date of birth #Checks if dobvalid_func returns true
if dobvalid_func(m,d,y)==0: print “Invalid date of birth” return 0
else:
age=cur_year-y-1
if m<cur_month or (m==cur_month and d<cur_day): age=age+1
return str(age)
The code for qty_mod is as follows:
# qty_mod.py
def qty_func(qtystr):
#Checks if the quanity entered is numeric #and whole number
i=0
while i<len(qtystr): c=ord(qtystr[i])
if (c in range(0,47) or c in range(58,255)) and c<>46: print “Please enter integers only”
break else: i=i+1 if i==len(qtystr): qty=float(qtystr) if qty<>int(qty) or qty<=0:
print “Invalid value for quantity”
The code for creditcard.py is as follows:
# creditcard.py
def credit_func(cardno):
#Checks if credit card no. is 16-digit and # contains only numbers
if len(cardno)<>16:
print “Credit card no. should be 16 digits” else:
i=0
c=ord(cardno[i])
if c in range(0,47) or c in range(58,255): print “Please enter integers only” break
else: i=i+1
You need a module to verify that the validation modules that you have created execute properly. The code for this purpose in main_mod.py is as follows:
import isblank_mod import qty_mod import creditcard import age_mod
fname=raw_input(“Enter your first name: “) #Call isblank function for fname
isblank_mod.isblank(fname)
lname=raw_input(“Enter your last name: “) #Call isblank function for lname
isblank_mod.isblank(lname)
date=raw_input(“Enter your date of birth, mm-dd-yyyy: “) #Call age_cal function from age_mod module
return_age=age_mod.age_cal(date) if return_age<>0:
print “Your age is %s years” %(return_age) qty_order=raw_input(“Enter quantity: “) #Call isblank function for qty ordered if isblank_mod.isblank(qty_order)==1:
# Call function qty_func in qty_mod module qty_mod.qty_func(qty_order)
credit=raw_input(“Enter credit card no.: “) #Call isblank function for credit card no. if isblank_mod.isblank(credit)==1:
#Call function credit_func in creditcard module creditcard.credit_func(credit)
Execute the Code
In order to implement or view the output of the code and test validation modules, you need to execute the following steps:
1. Write the preceding code separately for each module in a text editor and save all the modules with the .py extension in the current directory.
2. At the shell prompt, execute main_mod.py.
3. At the prompt Enter your first name:, enter Laura.
4. At the prompt Enter your last name:, press enter (leave it blank). 5. At the prompt Enter your date of birth, mm-dd-yyyy:, enter
6. At the prompt Enter quantity:, enter 6.3.
7. At the prompt Enter credit card no.:, enter 12219461263.
Summary
In this chapter, you learned the following:
■■ A module is a file containing Python definitions and statements used to organize code for easier maintenance. The filename is the name of the module with the .pyextension appended.
■■ The process of bringing in attributes, such as variables and functions, of one module into another or into the main module is called importing.
■■ The syntax of the import statement is:
import module1[,module2[,... moduleN]
■■ The global variables inside a module can be used as any other global variables; however, these variables will be local to that module.
■■ The reference to an object that is made using dotted attribute notation is called fully qualified name. This notation prevents an exact conflicting match in the cur- rent namespace importing module. The syntax for the notation is:
modulename.functionname
■■ A module can be imported by another module. The syntax of the from-import statement is:
from module import item1[,item2....[,itemN]]
■■ The from-import statement does not import the entire module. It imports only variables and functions from a module. Names imported in this way become a part of the current namespace. You alter a copy of the names, not the original. ■■ While importing a module, the predefined directories searched by the Python
interpreter constitute the Python search path. The module search path is stored in the system module sys as the sys.path variable.
■■ Loading a module executes the code in the top-level portion of a module, which usually includes setting up global variables and class and function declarations. If the module is executed directly as a script, any code inside the check for __name__built-in attribute of the module is executed. When the module is loaded by importing it, it is loaded only once even if it is imported multiple times. ■■ The dir() built-in function returns a sorted list of strings containing the
names defined by a module.
■■ The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from which they are called. ■■ The reload() function reexecutes the top-level code in a module.
■■ A package is a hierarchical file directory structure used to organize related- Python modules.
7
OBJECTIVES
In this chapter, you will learn to do the following: Use file objects
Use standard input and output methods Use methods of file objects
Use methods of the os module Use methods of the os.path module
Getting Started
In the previous chapters, you learned how to accept data from users and display it. What happens to this data when you quit the interpreter? All the user input values will be lost. How can you store data for future use? To store data for future use, you can redirect user input into a file. You can also read the contents of a file.
In this chapter, you will learn how to write and append data to a file. You will also learn how to read the contents of a file.