Python, the "def" function


#1

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.


#2

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


#3

Thanks but, when would i use def?


#4

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


#5

Thank you very much it!! It explains alot!
:grin:


#6

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)


#7

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


#8

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


#9

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