Page 129 - Computing E-Book Grade 7
P. 129

The City School  2021-2022



             Sample Code-1

            The sample code below demonstrates how functions are used in python:



             # This declares the function
             called my_function()

             def my_function():
                 print(“Hello from a

             function”)
             # Calling the function                                                                                  Programming the Computer-Python

             my_function()


             1.  Keyword def marks the start of function header.

             2.  A function name to uniquely identify it. Function naming follows the same rules of
                writing identifiers in Python.

             3.  Parameters (arguments) through which we pass values to a function. They are
                optional.

             4.  A colon (:) to mark the end of function header.
             5.  The last line executes the function, we can call or use the function in our code

                wherever it is needed.


             Sample Code-2



             # This declares the function
             called print_name()

             def print_name():
                 print(“Enter your name”)

                 yourName=input()
                 print(“Hi ”+yourName)

             # Calling the function
             print_name()


             Sample Code-3



             We have already experienced this code earlier but now we have converted the same
             into a function and now it can be recalled and reused whenever required in the

             program.







                                                                                                                129
   124   125   126   127   128   129   130   131   132   133   134