Python, the "def" function

Hello , im kinda new to the codecademy and ive started to learn python. It has been great but i just can’t seem to understand the def function.

Sorry if it seems like a dumb question, or ive maybe placed it into a wrong category idk.

But if someone can help me out , please id be grateful.

def is a keyword in the python language, the def keyword allows us to define a function

1 Like

Thanks but, when would i use def?

When you want to define a function. Functions are very useful, you will see as you progress through the course. We can use it for repetitive tasks (with slight variation if we want), or if we need to do something later.

lets say you build a calculator, you don’t know what operators the end user will do. So you can define function to do the necessary operations, and call the appropriate function when you want to use it

1 Like

Thank you very much it!! It explains alot!

If just write code like so:

print "hello"
print "world"

it will execute from top to bottom, the great thing about functions is that we can execute in order:

def one():
   print "world"

def two():
   print "hello"

two() # will print hello
one() # will print world

also, imaging make a website. You don’t know which pages the user might visit, so you need different function to load different pages (sort of)

1 Like

So basicly when i define a word , put code below it, every time i say(type) that word the code will be executed?

the last two lines of the code i posted are function calls, they execute the function. You can call one function multiple times. We can even pass values to the function when calling it:

def say_name(the_name):
   print "hello " + the_name

say_name("stetim94") # will print hello stetim94
say_name("m4rkoxx") # will print hello m4rkoxx

but you will get more on this later on


Dude thank you so much, you explained alot to me and even wrote little code to help me understand more. Thanks alot!!!