functions

functions

In below example, we have defined a function using the def command that will print out the numbers between 1 and 10 whenever it is called:

def count_to_10():
   for i in range(1, 11):
      print(i)

count_to_10()


If we wanted to count up to any number, then we can include the maximum number as a parameter to the function:

def count_to_n(n):
   for i in range(1, n + 1):
      print(i)

count_to_n(5)


This can be improved, for example, if we want that by default count to 10, unless a different number is specified:

def count_to_n(n=10):
   for i in range(1, n + 1):
      print(i)

count_to_n()        <--it will count to 10
count_to_n(5)       <--it will count to 5


If your function needs more than one parameter, for example to count between two numbers, then the parameters are separated by commas:

def count(from_num=1, to_num=10):
   for i in range(from_num, to_num + 1):
      print(i)

count()               <--it will count from 1 to 10
count(5)              <--it will coutn from 5 to 10
count(3,7)            <--it will coutn from 3 to 7

==========================================

return

If you need a function to return a value, you need to use the return command.

The following function takes a string as an argument and adds the word please to the end of the string.

def make_polite(sentence):
   return sentence + " please"

print(make_polite("Pass the cheese"))

When a function returns a value, you can assign the result to a variable, or as in this example, print out the result.

No comments:

Post a Comment