Skip to main content
Python 3Scripting

Defining Functions in Python

By April 17, 2013No Comments

As our scripts go, we are going to find the need to use functions, reusable blocks of code. In the project script that we are working with, we create users from the command line input but will also need to be able to read in users from files. We could duplicate the code in both areas but maintaining the script then will become a nightmare. This is where we introduce user defined functions or blocks of code we create. Very simply, functions are defined with the def keyword and can be written to accept input parameters but they do not have to:

		def to_lower(text):
		to_lower("Some Text")

The reality is the above function does not do too much other than use the two built in functions lower() and print(), but as an idea of how to use functions it is a start. We can also make use of the lower() function of string objects to make sure that out user accounts are created in lower case.

		def grep(text,file):
			f = openfile(file)
			for l in f.readlines():
				if l.startswith(text):

This function is starting to get a little cute, cloning some functions that we may usually use the binary grep for. Of course, we could still use the actual grep program using os.system, however keeping it to functions, especially built-in functions, is generally going to be more resource friendly. Our user defined function grep accepts to parameters, text and file. We search for the text in the file and for the line beginning with the text. We can use this in our main project file to display the user once it has been created.