hi, guys I'm completely new with python and right now struggling when it comes to creating functions....i have to do the following for an assignment if anyone can help that'll be awesome.

Create a function that take a full name as a parameter and returns just the middle name regardless of how many words it consists of????

i am looking for a function!

Defining a function is easy.

def sayHello():
    print "Hello World!"

That's quite simple. Next you need to send it a parameter:

def sayHi(name):
    print "Hello " + name

The previous function could be call as:

sayHi("Michael Jordan Jones")

And it would return "Hello Michael Jordan Jones". Now you need to get the middle name. First let's set a system for doing so:
1) Get full name
2) Split string to get each name
3) Find the middle name
4) Return it

Step one is done by passing the function a parameter. Splitting the string can be done with the .split(' ') function to split it at spaces. To find the middle name you have a decision to make: if it's odd your fine, but what do you do if there is an even number of names entered? I'll leave that one up to you. :D Returning it is just using the 'return' statement.

So, in total you may end up with something like this:

names = name.split(' ')
if len(names) % 2 == 1:
    return names[int(math.ceil(len(names)/2))]
else:
    return "You're on your own here.  ;)"

I hope I've guided you in the right direction. Best of luck!

- WolfShield

def middle(name):
    names = name.split(' ')
    if not (len(names) <=2):
        middle_names = names[1:-1]
        return ' '.join(middle_names)
    else:
        return 'There is no middle name in %s'%name

print middle("Michael smith Jordan Jones")
print middle("Michael Jordan Jones")
print middle("Michael Jordan")
print middle(raw_input("Enter a name"))

Note: it is assumed that the "name" entered has no extra spaces.

Version of M.S. code that can cope with extra spaces:

def middle(name):
    names =[n for n in name.strip().split(' ')  if n]
    if not (len(names) <=2):
        middle_names = names[1:-1]
        return ' '.join(middle_names)
    else:
        return 'There is no middle name in %s'%name

print middle("Michael smith Jordan Jones")
print middle(" Michael    Jordan  Jones  ")
print middle("  Michael    Jordan  ")
print middle(raw_input("Enter a name: "))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.