1,760
edits
Changes
→PART 1 - How User-Defined Functions are Declared and Run
:# function that takes function argument((s) and also return value(s)
== PART 1 - How User-Defined Functions are Declared and Run Function that does not take argument or return value ==
'''Functions and Strings'''
: You will now learn how to define and run functions that will return print '''string data''' to standard output (default to screen) when a function is called.
:'''Perform the Following Steps:'''
:#Create a new python file for testing code in this section.
:#Whenever you want to create a function, you must start with the keyword "'''def'''". The '''def''' keyword is used to start the definition of the function, it does not run the code you writeright wary. Functions, just like '''if''' statements, must have all code under them indented.<source lang="python">
def hello():
print('Hello World')
print('Inside a Function')
</source>
:#Executing your file you should have noticed that nothing happened. Well actually, something did happen... the function called '''hello(''') has been defined and stored in internal process's memory in order for it to run when called by its function name. Now that our function was created, we can use it over and over.:#To execute the code inside the function, run the function name with "'''()'''" '''brackets''' at the end of the function name.<br>Try running calling the '''hello()''' function by name three times by adding the following three lines after the function declaration, like this:<source lang="python">def hello(): print('Hello World') print('Inside a Function')
hello()
hello()
hello()
</source>You should notice that the function just does the same thing over-and-over no matter how many times your call the function by name. By the way, that is OK. On the other hand, you may want to create and use a function to do something, like perform error checking or some other task that returns a value report back to the '''maincaller''' program for further processing. For example, a '''true''' or '''false''' value if the error checking function that was called was detected no errors or detected an error. But let's stick to some simple examples first, before tackling more complex use of functions.In Python, when a function does not return a value, it will return a special Python object called "None". "None" is a Python 3.x keyword which is used to indicate that there is "nothing". Let update the above Python script to the following version:<source lang="python">def hello(): print('Hello World') print('Inside a Function') my_stuff = hello()print('Stuff return from hello():',my_stuff)</source><br><br> == PART 2 - Function that does not take argument but return a value ==
:#Let's create a function that '''returns''' some data after the function is called. This function does not print out any text: instead; it creates new variables and at the end returns the value of one of the variables.<source lang="python">
def return_text_value():