Why Do We Need Functions?
Let's say that we need to have a program that asks, say, 5 people for their names, displays different messages for each, and adds them to a list. We could do this with copy/paste:
firstNames = []
lastNames = []
first = input("Person 1's First Name:")
last = input("Person 1's Last Name:")
print("So great to see you, %s %s!" %(first,last))
firstNames.append(first)
lastNames.append(last)
first = input("Person 2's First Name:")
last = input("Person 2's Last Name:")
print("Go %s %s!" %(first,last))
firstNames.append(first)
lastNames.append(last)
first = input("Person 3's First Name:")
last = input("Person 3's Last Name:")
print("%s %s, you're awesome!" %(first,last))
firstNames.append(first)
lastNames.append(last)
first = input("Person 4's First Name:")
last = input("Person 4's Last Name:")
print("Woohoo for %s %s!" %(first,last))
firstNames.append(first)
lastNames.append(last)
first = input("Person 5's First Name:")
last = input("Person 5's Last Name:")
print("You're awesome, %s %s!" %(first,last))
firstNames.append(first)
lastNames.append(last)
That's reeeeeeeeeeeeeeeeeeeeeeeally long, 32 lines. Here's a shorter method:
num = 0
def hi(message):
num = num + 1
first = input("Person %s's First Name:" %(num))
last = input("Person %s's Last Name:" %(num))
print(message %(first,last))
firstNames.append(first)
lastNames.append(last)
hi("So great to see you, %s %s!")
hi("Go %s %s!")
hi("%s %s, you're so awesome!")
hi("Woohoo for %s %s!")
hi("You're awesome, %s %s!")
This is only 13 lines, a huge improvement. You'll learn how to do this right below.