Functions are very useful for programing in python. First they cut down code. For instance you could write.
|Yes I know there is inbuilt things for powers but might as well go whole hog here|
|Now with annoying color|
Hit enter twice and you'll be back to "ground level" in the shell. Now we're going to have some problems here due to blog not doing tabs right. Python for functions and scopes require indentation with whitespace, for blog code I'll use spaces, for real coding my preference is tabs. Either way I'll include what I did to the right so I can explain it a bit with graphical aids.
First you have to use def, underlined in red I'll explain why it's important latter, to create the method. After that is your methods name, it can be any thing as long as it is "one" continuous block of characters and avoids some special characters. Dashes are fine though otherwise not so much and I haven't tempted fate enough to learn the results. A space after that is your parameters or arguments underlined in green. In it's simplest form you can use as many as you want or as little as you want, even none you just put (), but you have to give them a name like any other variable and separate them with a comma. Trailing this is the colon which is the first indication of a change in scope. What this means I'll get back to later.
The right_triangle method we created is rather simple. It only has one line of code after it with a return statement followed by things I underlined in yellow. I'll get to that in a second but first lets use the method. Please type the following.
|with the power of cropping you'll not see the mistake!|
Admittedly this would be more impressive if the text to invoke right_triangle was less than the straight up code with the numbers that it produces. Methods allow you to reuse code and return results. Before there was the underlined piece of code with the variables a and b in it. The a and the b were the arguments passed when right_triangle was invoked in the code. The reason you have to use all the variables is that the code expects them. In the scope after it a will effectivly be whatever is passed first while b is whatever passed second. Now they don't have to be named a,b,c or any sort of sequence. Like the functions name you can name them whatever you wish as long as you separate with commas and enclose with parenthesis.
Now this doesn't have to be one line long. It can be multiple lines as long as the indentation is correct. For example.
Now this wasn't a very useful function. As I said before you could type out what it was doing in less typing than it took to make it, but once it starts getting lines long or used for other things that involve later ideas it'll start looking like a good choice. Till then hopefully I didn't butcher this idea too badly.