When should functions generally be created?

Question

In general, when should functions be created in the code?

Answer

It is usually best to create a function if some process or calculations in code have to be repeated multiple times.

Creating a function will save you time from having to rewrite code lines over and over, by only having to write them once within the function. Furthermore, this can keep the code cleaner and more concise, which also will improve maintainability of the code, since we would only have to look at the code in the function one time when debugging.

30 Likes

Can’t you just assign some text to a variable?

That would be a literal assignment. What of a dynamic one?

4 Likes

Whenever we define a function, do we have to write def in the beginning?. For example, in the exercise it starts with def greet_customer():. Also, why colons are used after the parentheses?.

8 Likes

the def keyword is mandatory when defining a function, unless you want to get an error when running your code. Next, : (colons) are to indicate a code block that belongs to that line. You must indent after a :.

#this is my function
def my_function(): # <- :  means we must indent. it belongs to the function
       print("Im a part of this function") 

print("Hello! Im not a part of this function!") 

#this code isn't indented the same level as the previous print is...
# It doesn't belong to the function.

: are used in for loops, if/elif/else conditional statements, and others that you will learn later.

I hope this helps.

30 Likes

Thanks…it’s clear now

2 Likes

Thank you for this great answer.
But I just want to confirm that for any code block (function, for loops etc), after the : any lines that are indented become part of that code block, right?
Then to break the code block we just stop the indentation?

That is correct. It’s important that indentation is consistent for each block level.

def func():
    for ...:
        if ...:
            # code
        else:
            # code
    return ...
6 Likes

Hello,

Can someone explain to me what the difference is between calling a function and printing a function?

2 Likes

What is the use of def

def is short for define. It is a fundamental keyword in the creation of function objects.

>>> def foo(bar):
  try:
    return bar + 1
  except:
    try:
      return 'foo' + bar
    except:
      return bar

>>> foo(1)
2
>>> foo('bar')
'foobar'
>>> foo([])
[]
>>> 
1 Like

What is the difference between print and call?

They are very different. When we write, print (expression) we are calling the print() function with the argument, expression. A call is the invoking of a function.

 def foo (bar):
    return bar

 print (foo('bar'))    //  prints 'bar'

Above we invoked the print function on the return value of the call to foo().

2 Likes

There are a number of other reasons to put code into functions. One is to make code more self documenting and easier to read via the name of the function. The name of the function tells you what it does (or what it should be doing at least) meaning you won’t have to look at the code to get a general understanding of what it does.

Another reason in Python is if you want to import the code. When importing modules in Python the code in it is run, if you don’t want code to run when it is imported it should be in a function (or class or some such) so that what is run is the creation of the function. This is why you will often see:

if __name__ != "__main__":

name will not equal “main” when the file is being run when imported.

3 Likes

exactly, a function.

There is a task to display stanza of lyrics two times.
Here is a code,

def sing_song():

print(“You may say I’m a dreamer”)

print(“But I’m not the only one”)

print(“I hope some day you’ll join us”)

print(“And the world will be as one”)

sing_song()

sing_song()

Query : But when I done this stanza displayed twice as mentioned in the task. But it displayed without a gap between 1st stanza and that repeated same stanza.
How to display gap between two stanzas ??

1 Like

There’s a few ways to do this but it boils down to the fact you want to send an empty line to the output between your two function calls.

Note that print has a default argument of end='\n' which introduces a newline character (this is why each of your lines with print end up on a new line when represented in the output). See the docs for details- Built-in Functions — Python 3.9.1 documentation

Therefore a simple route is using print without arguments between the two function calls, print() which will send only the end and lead to a new line. Another alternative would be altering the last print call in your function to send two new lines print("And the world will be as one", end='\n\n') if you always wanted an extra gap (consider what works best with the rest of the code).

1 Like

Thanks so much tgrtim

1 Like