[Tutor] Python Question

Alan Gauld alan.gauld at btinternet.com
Fri Jan 10 11:19:44 CET 2014


On 10/01/14 00:11, Amy Davidson wrote:
> Hi,
>
> I am a university student who is struggling with writing functions in Python.

You could try reading the functions and modules topic in
my tutorial.(see below)

> 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)

The def printID bit is fine but you were supposeed to have *parameers* 
fore name and student number. A parameter is like a variable, its a 
generic name that you later assign a value to when you call the function.

Thus here is a simple function that adds 5 to the number
passed to it

def add5(n):
    ...

First, note the colon after the function definition, that's important.
Now, n is a parameter, a place marker that we can use inside
our function. When we call add5() we provide a value, called
the argument:

result = add5(3)

Now inside the add5() function n has the value 3.

So for your function you need to provide two parameters called,
maybe, say, 'student' and 'studentN'? (It's traditional to have
parameter names start with lower case letters. Python doesn't
care but it makes it easier for other programmers - or you
later on - to recognise what they are)

> Student = “Amy Davidson”
> StudentN = 111111111
> print (“StudentName:”, Student)
> print (“StudentNumber:”, StudentN)

The lines that make up a function body must be indented under
the def line. For example in my add5() example it would look
like:

def add5(n):
     return n+5

So your four lines above need to be indented, and once
you create parameters the first two will not be needed.

Once you have that down you can then test your function by calling it 
with whatever values you want printed:

printID("Amy Davidson", 111111111)
printID("Bill Gates", 12345678)
etc...


hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list