Functions in Python

Now that we have an understanding with all the basics mentioned so far, it's time to meet an elegant custom 'tool': FUNCTIONS. What is a function you ask? I'll give you an example. Assume that we're designing an advanced calculator for mathematics. At certain time we need to do a calculation for solving a quadratic formula. Instead of writing the whole code every time we need to solve that quadratic formula, we write it once and put the code into a function with a distinct name. When this function is been called will spit out the result of the corresponding formula. That's it.

Basic Syntax without Parameters

def functionName():
      ..........
      ...code...
      ..........
      return something

Basic Syntax with Parameters

def functionName(parameter):
      ....parameter + operation....
      ...code...
      ..........
      return something or parameter

Sample Function (without parameter)

This function asks the user to insert a string (phrase as you can see), adds another string to it, and then returns it. In this case, the moment the value is been returned enters as an element into 'myList'. The bold text bellow represents the call of the function stringToList() which we've created.

>>>   def stringToList():
          value = raw_input('Enter string: ')
          value + '!'
          return value

>>>   myList = [34, 54, 98, 'Hello', 'Yeah']
>>>   myList.append(stringToList())   We call the function by name
Enter string: hello   We are inside the function
>>>   myList
[34, 54, 98, 'Hello', 'Yeah', 'hello!']

exercise-icon Try it!

Create a function named divisionPy() which will make a simple division and return the result. Inside the function, declare a variable named samples and set it to 10. Return the division of that variable with 1000.


?

Sample function (with parameter)

This function is been called with a variable passed from the user along with its name. Takes the user's number and prints all numbers in series until reaches that number.

>>>   def cSeries(num):
          for item in range(1,num+1):
              print item
>>>   cSeries(10)   We call the function by its name and a number
1, 2, 3, 4, 5, 6, 7, 8, 9, 10

exercise-icon Try it!

Develop a function named squareNum() with parameter a var named num. Inside the function, return the square of this parameter.


?

exercise-icon Pop Quiz

Develop a function named eqSolve with parameters: Parameter one will be named numBase and the other Target. This function will generate all numbers in series from the base number (parameter #1) up to the Target number (parameter #2). See Note for main structure.



?
python.org | Contact Me | © ksoftware.eu 2016