[Tutor] Python Question

spir denis.spir at gmail.com
Fri Jan 10 11:43:29 CET 2014


On 01/10/2014 01:11 AM, Amy Davidson wrote:
> Hi,
>
> I am a university student who is struggling with writing functions in Python. I’ve been attempting to write a function in Python for over 2 hours with no progress. The function must be called, printID and take a name and student number as parameter and prints them to the screen.
>
> This is my closest guess:
>
> def print_ID(“Amy Davidson”, 111111111)
> Student = “Amy Davidson”
> StudentN = 111111111
> print (“StudentName:”, Student)
> print (“StudentNumber:”, StudentN)
>
> If you could help correct my work and explain, that would be great!
>
> Thanks,
>
> Amy Davidson

You are confusing *defining* a function and *executing* it. Below a trial at 
explaining. You may have a part of program that does this:

	name = "toto"
	ident = 123

	print(name, ident)	# the performing part

Now, say instead of a single line, the "performance" is bigger or more 
complicated and, most importantly, forms a whole conceptually. For instance, it 
may be a piece of code that (1) reads and properly structures input data or (2) 
processes them or (3) outputs results in a format convenient to the user. If you 
structure program application that way, then it looks like

	data = read_input(where)
	results = process(data)
	write_report(results)

which is quite clear, isn't it? Functions (procedures, routines, etc...) are 
used first to provide such a clear structure to a program, which otherwise would 
be a huge mess. Another reason why functions (etc...) are necessary is that one 
often uses pieces of code multiple times, maybe millions of times even when 
applying the same process to a big store of data. Yet another reason is to build 
a toolkit for standard or common tasks, that one can reuse at will when needed 
--and that's what a language comes with: standard / primitive / builtin routines 
for the most common tasks. And then we construct more sophisticated processes 
from these building blocks, according to our app's needs.

Now, back to concrete. To define and use a function, one proceeds as follows 
(example):

# define function:
def average (numbers):
     count = len(numbers)    	# len means length"
     total = sum(numbers)
     return total / count

# use function:
nums = [1,3,9]
x = average(nums)
print(x)    			# ==> 4.333333333333333

You first define the function using a "def" instruction. The function nearly 
always takes some input variable(s) called "paramaters", here 'numbers'. And 
often returns a result [*].

I think and hope you have enough information to do it in your case; and in a 
variety of other cases you may like to try and play with :-)

Denis

[*] Else, rather than a function properly, it is an action that *does* something 
but usually does not return any result. For instance, 'write_report' above is an 
action.




More information about the Tutor mailing list