Lecture 7 Functions and the Control Flow

1. Type conversion
Python provides a collection of built-in functions that convert values from one type to another. The int function takes any value and converts it to an integer, if possible, or complains otherwise:


int can also convert floating-point values to integers, but remember that it truncates the fractional part. The float function converts integers and strings to floating-point numbers. Finally, the str function converts to type string:


It may seem odd that Python distinguishes the integer value 1 from the floatingpoint value 1.0. They may represent the same number, but they belong to different types. The reason is that they are represented differently inside the computer.

2. Math functions
Before we can use the functions from a module, we have to import them:



To call one of the functions, we have to specify the name of the module and the name of the function, separated by a dot, also known as a period. This format is called dot notation.



How can we import 'pi'? Well, there are many ways we can do it. We can import it from the 'math' package. The constant pi is also part of the math module.

Keep in mind it starts from 'FROM' but not 'IMPORT' here:


If you already had 'from math import pi', then you do not need to type 'math.pi' all the time to use 'pi' in your code. Just type 'pi' will work. Otherwise, you will need 'math.pi' all the time.

For square root:


3. Composition
Just as with mathematical functions, Python functions can be composed, meaning that you use one expression as part of another. For example, you can use any expression as an argument to a function:

You can also take the result of one function and pass it as an argument to another:


4. Adding new functions (user defined functions)
So far, we have only been using the functions that come with Python, but it is also possible to add new functions. Creating new functions to solve your particular problems is one of the most useful things about a general-purpose programming language. In the context of programming, a function is a named sequence of statements that performs a desired operation. This operation is specified in a function definition. The functions we have been using so far have been defined for us, and these definitions have been hidden. This is a good thing, because it allows us to use the functions without worrying about the details of their definitions. The syntax for a function definition is:

def NAME( LIST OF PARAMETERS ):
    STATEMENTS

You can make up any names you want for the functions you create, except that you can’t use a name that is a Python keyword. The list of parameters specifies what information, if any, you have to provide in order to use the new function. There can be any number of statements inside the function, but they have to be indented from the left margin. In the examples in the textbook, the indentation is two spaces.



The function call in the last line 'printSomething()' is not indented, Python knows that it is not part of the function.

5. Flow of execution/parameters/arguments

In order to ensure that a function is defined before its first use, you have to know the order in which statements are executed, which is called the flow of execution. Execution always begins at the first statement of the program. Statements are executed one at a time, in order from top to bottom.

Here is an example of a user-defined function that has a parameter:


You can even 'times four' to the input.


Please keep in mind that the variables and parameters are local. There is no 'bruce' outside of the 'printSomethingTwice(name)' function.

6. Control flow tools: Conditionals and recursion

6.1 The modulus operator


6.2  Boolean expressions
A boolean expression is an expression that is either true or false. One way to write a boolean expression is to use the operator ==, which compares two values and produces a boolean value:


In the first statement, the two operands are equal, so the value of the expression is True; in the second statement, 5 is not equal to 6, so we get False. True and False are special values that are built into Python. The == operator is one of the comparison operators; the others are:


Although these operations are probably familiar to you, the Python symbols are different from the mathematical symbols. A common error is to use a single equal sign (=) instead of a double equal sign (==). Remember that = is an assignment operator and == is a comparison operator. Also, there is no such thing as =< or =>.

6.3 Conditional execution: (the if statement)
The boolean expression after the if statement is called the condition. If it is true, then the indented statement gets executed. If not, nothing happens.


6.4 Alternative execution:
A second form of the if statement is alternative execution, in which there are two possibilities and the condition determines which one gets executed. To put the code into a function:


6.5 Chained conditions
elif is an abbreviation of "else if". Again, exactly one branch will be executed. There is no limit of the number of elif statements, but the last branch has to be an else statement


6.6 Nested conditionals
One conditional can also be nested within another. Achieve the same results as above but using a nested 'if statement':


6.7 The return statement:
The return statement allows you to terminate the execution of a function before you reach the end. One reason to use it is if you detect an error condition:


The function printLog has a parameter named x. The first thing it does is check whether x is less than or equal to 0, in which case it displays an error message and then uses return to exit the function. The flow of execution immediately returns to the caller, and the remaining lines of the function are not executed.

Look at the following example to understand how the 'return' works in Python: (read the comments in the code)


6.8 Recursion
Look at the function below:

Countdown expects the parameter, x, to be a positive integer. If n is 0, it outputs the word, "Blastoff", Otherwise, it outputs 'n' and then calls a function named countdown itself passing n-1 as an argument.

6.9 Keyboard input
Python provides built-in functions that get input from the keyboard. The simplest is called 'input()'. When this function is called, the program stops and waits for the user to type something. When the user presses Return or the Enter key, the program resumes and raw input returns what the user typed as a string:


6.10 Fruitful Funtions:

Return values

Not only can you pass a parameter value into a function, a function can also produce a value. You have already seen this in some previous functions that you have used. For example, len takes a list or string as a parameter value and returns a number, the length of that list or string. range takes an integer as a parameter value and returns a list containing all the numbers from 0 up to that parameter value. Functions that return values are sometimes called fruitful functions. In many other languages, a function that doesn’t return a value is called a procedure, but we will stick here with the Python way of also calling it a function, or if we want to stress it, a non-fruitful function.


If the 'return temp' is not included in the function, then you will get nothing out of the function. So the 'returned' value is like the output of the function.
In Matlab, in the independent function module, we do this:

function   result = usrFunction(x)
            result = x^2;
end

'result' is the returned value from this function in Matlab. However, in Python, we don't put the returned value on the top, but we use 'return  something' to deliver the results.

In the example aboeve, if we don't have 'return temp', and leave that line empty, you will get this:


ALSO, the variable 'temp' is a 'local' variable, you cannot see it or use it outside of the function module. See the example below, after I run the function, and then I tried to call the variable 'temp' but I got nothing out of it. It is a local variable only being used inside of the function.

THIS IS DIFFERENT FROM MATLAB.



Since the value in 'temp' was retuned, it doesn't mean you can use 'temp' outside of the function (since it is a local variable). Keep in mind that the function is like a factory. Raw materials go into the factory and the product come out from the factory. The inputs are raw materials or variables, the output is the product or the returned values. There migh be many things or byproduct being produced in the facotry at the same time, but as long as the factory doesn't sell these things, they are internal things and other people won't know what are they.



So you may only care about the INPUT and the OUTPUT of the function, and the output must be returned to be able to become visible to the outside world.
If I call the function outside, and assigne the results (returned value) to a variable, then I can visualize this variable by just calling it.


As the example above, in order to take out the returned value and display it, you need to assign the function to a variable outside of the function itself.

An example of calculating the distance between two points in the coordinate
Suppose you want to find the distance between two points, given by the coordinates (x1; y1) and (x2; y2). By the Pythagorean theorem, the distance is:




As the example above shows, the name of the variable outside of the function doesn't have to be the same as the one inside the function. However, when you call the function, definitely the name you call must be the same name as the function.

Composition
You can call one function from within another. This ability is called composition. The following example is to calculate the area of a circle that using the distance between (X1,Y1) and (X2,Y2) as the radius.





All the arrows show you the flow of  how these parameters are bing passed throughout the functions when you call one of these functions and put the parameters in the function.

Boolean functions



Tasks:
1. Convert variable data types
a. Convert string "232" into an int variable.
b. Convert int '911' into a string variable.
c. Convert a floating variable '1.2222' into an int variable.

2. Use the 'math' package in Python to calculate:
a. 200*log10(100)
b. 15*sin(0.5*pi)
c. 10*tan(1.5*pi)
d. 5*e^(log10(5))

3. Use user-defined functions to complete the following tasks: (the logical operators of Python can be found at the bottom of this page)
a. Define a user-defined function, 'scoreCalculator(score)'  that can carry a score and calculate the grade of the score and print out the grade in IPython :
if score >=90, print the grade as 'A'.
if 90 > score >= 80, print the grade as 'B'.
if 80 > score >= 70, print the grade as 'C'.
any score less than 70 is 'F'.

b. Define a user-defined function, 'dataCheck(data)', to check if the parameter in the function is an integer or a floating point data. If it is an integer, check if it is >= 50, then print("You win the game"), if it is less than 50, then print("You lose the game"). If it is a floating point data type, then print("Please provide a valid number").
(the embedded function isinstance(number, datatype) can be used for the datatype judgement)

4.
Define a user-defined function to check the parity of a number. The number provided is normally an integer but the function must be able to tell the user if the input is a floating or int type number.

5. Design a function (recursion) to calculate the factorial of any given integers.

6. Define a function that carries the radius (r) and height (h) of a cylinder. This function calles two sub-functions which calculate the area of the cross-sectional circle and the volume of the cylinder separately.

7. The input from the user has three parameters: 'W' is the width of the rectangle, 'L' is the length of the rectangle, 'R' is the radius of the homogenious circles to he aligned one-by-one inside the rectangle.
a. Design a function that calculates/returns how many circles can be physically fit into a rectangle with given 'W' and 'L'. (Must use sub-functions to calculate how many circles width-wise and how many circles length-wise and use another function to calculte the entire number of circles).


b. Design another function to calculate/return the footprint of the empty area not occupied by the circles in the rectangle. The footprint of the empty area is equivalent to how many circles (use a function to calculate it)?




References: