Python3 tutorial - 3 (functions)

Python3 tutorial - 3

-------------------------------------------------------------------------------

Hello, and welcome to my tutorial - 3,
Lets get started !

So, 
lets meet a new topic, functions() 
these are blocks of code which can be used multiple times in our script to do a specific task in a specified manner,

definitions of a function starts with a def keyword, 
like this:




we can see in the picture that the function "function" ends with "()"
and a ":",
in the "()", we have to give any needy inputs (if any), but in the function(), we don't need to use any external variables, thus we wrote it as "function()", whereas ":" marks the end of name of the function and start of body of it, 

Note: we must indent the body of function or leave some whitespaces and then write the body, like we did in if-else
statements  

have a look at this picture where we are giving some variables to act on:





here, our area function takes 1 argument at the time when we call it like, area(5) and at the time of declaration we wrote a variable side which was to calculate the area, side**2 is the square of side variable and is raised to power of 2 by the operator **,

here, we are actually declaring a variable with no value b/w the "()" of the function at the time of declaration of function and giving that variable a value when we call the function,

functions save programmers a lot of time and are a major way of code reuse, 
remember 5R's !

okay, so lets think about a different situation where we want to assign the area of the square we calculated above to a variable say area, this can't be done by the print() function, it just prints a value to the screen passed as argument b/w "()", this can be easily done by a keyword "return" which is used only for this purpose and doesn't prints any value to the screen, 

like this:


in this example, the area function returns side times side that is area and that returned value is captured by our new variable area,

lets try to see what happens when we try to do this with the previous area function which didn't used the print function,


here, the output was 25 due to the print statement and as nothing was returned, the area variable wasn't assigned any value and when we tried to print area on the screen, it printed None which indicates absence of values,

so I think it was enough for today, 
Bye for now, 
catch me later on python3 tutorial - 4

Comments