Search

Carolina's Blog Site

I use this blog to share my experiences in learning how to program, among other things.

Month

September 2016

Function: GCD (Giant Chocolate Donut)

So today I made a function that asks the user for 2 integers and then displays the Greatest Common Denominator, which is the largest number that divides both of them without leaving a reminder. I realized there’s several ways to do this, but I think this one’s pretty simple. It took me awhile to get it though. I just couldn’t make sense of it! Thank goodness I have fellow programmer friends who can explain theses sorta things to me 🙂

Why you should care about functions.

A function is a named sequence of statements that performs an operation/computation. Functions may or may not take arguments (which are like the ingredients that change depending on what result you want to achieve in that particular occasion).

To define a function,

  • you write def followed by the name of the function,
  • then you write the parameters/arguments in () and you end with a “:”
  • In the body of the function, which has to be indented, you type the order of the statements you want that function to do.
  • To finish off a function, type return and specify what the function will return. If you don’t want to return anything, just leave the return line blank with (). Any code after the return statement will not happen.

Later, you can “call” the function by its name, and just type the parameters for that occasion. I know, awesome!

Side note:

  • Parameters can have a default value, for example: (parameter1, parameter2, parameter3=55).
  • If a function is a thing and parameters can be anything…then functions can also be used as parameters of other functions.
  • In a repetitive algorithm, you may need to use recursion, meaning you call a function inside that same function.

pic souce: http://www.relatably.com/m/functional-programming-memes

 

 

Fortune cookies are so last century.

So my goal for this rainy afternoon was to write a program that simulated a fortune cookie. I did it using lists, the import statement and the while statement. So…when you press enter, the program displays (prints) 1 of 5 unique fortunes, randomly, each time.

 

Blog at WordPress.com.

Up ↑