Sunday, February 18, 2018

Functions

Functions are name blocks of code that can be called multiple times through the program and are designed to do a particular job.

def greetings():
       print("Hello World")

greetings()

Output: 
Hello World

Passing information to a function:
def greetings(myGuest):
   print("Hello, " + myGuest + "!")





greet_user('Programming Clue')

Output: 
Hello, Programming Clue!

Passing multiples arguments:
def favTeam(teamA, teamB):
   print("\nMy favorite team is " + teamA + ".")
   print("But I also like " + teamB + ".")

describe_pet('Real Madrid', 'FC Barcelona')

Output:
My favorite team is Real Madrid.

But I also like FC Barcelona.

We can also do this:
describe_pet('Arsenal', 'Miami Heat')

and re-use the function again


Use functions to return a value:
def getMyFavTeam(teamA, teamB):
      myTeams = teamA + ' ' + teamB
      return myTeams
soccer = getMyFavTeam('Real Madrid', 'Betis')
print(soccer)       
       
Output:
Real Madrid Betis

Using a function-while loop
def fullName(firstName, lastName):
   fullName = firstName + ' ' + lastName
   return fullName

while True:
   print("\nPlease tell me your name:")
   print("(enter 'q' at any time to quit)")
   firstName = input("First name: ")
   if firstName == 'q':
      break;
   lastName = input("Last name: ")
   if lastName == 'q':
      break;
   fName = fullName(firstName, lastName)
   print("\nHello, " + fName + "!")

Output: 
Hello, Peter Roman!

Please tell me your name:
(enter 'q' at any time to quit)

First name: 

Passing a list as argument:
def students(names):    for i in names:    greetings = "Hello, " + i + "!" print(greetings)
classAttendance = ['Pippen', 'Jordan', 'Bryant']students(classAttendance)




Output:
Hello, Pippen!
Hello, Jordan!
Hello, Bryant!






No comments:

Post a Comment