Lecture 8 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.

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:

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 calate 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 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 float type number.

References: