Chapter 11-
Functions, Conditional Statements and Loops
Functions
A function in Python is a group of statements that take input, perform certain calculations, and generate output. The idea is to combine everyday tasks to perform a specific function, with the aim of calling the service instead of writing the same code multiple times for different inputs. Python comes with built-in functionalities, but developers can still add their own purposes, commonly referred to as user-defined functions.
An example of a simple Python function to check whether a certain value is an even number or an odd number is:
- def evenOdd(x):
- if (x % 2 ==0):
- print "even"
- else:
- print "odd"
- # Driver code
- evenOdd(2)
- evenOdd(3)
Developers should understand that, in Python, the name of every variable is a reference. Therefore, when they pass a variable to a particular function, they will create a new reference to the object. Essentially, it is Python's version of reference passing in Java.
Functions in Python are essential when it comes to data analysis and machine learning. They save time and effort applied in coding. In other words, they allow developers to reuse a specific subset of code in their program whenever they need to. A primary function contains the following things:
1. Code that the developer wants certain functions to run whenever they call it
2. Function name to use when calling a particular function
3. Def keyword to let the program know when developers are adding their own functions
Essentially, when developers want to use a certain function, they simply call it using its name followed by parenthesis, i.e., function name (), for example, if
the aim of the function is to print the word 'Thanks' with the name of the user, the developer can use the following code:
def func(name):
print("Thanks" +" " + name)
Whenever the developer needs to call this function, all he/she needs to do is pass its name as a parameter in string format, which will generate the desired output. For example, func("Paul") will return "Thanks Paul."
On the other hand, if a developer wants a function to generate a value, he/she can define it as follows:
- def square(value):
- new_value = value ** 2
- return new_value
- Output-
- number = square(4)
- print(number)
- 16
Developers can also define default arguments to return the predefined default values if someone does not assign any value for that argument.
It is normal to wonder why it is essential to use functions for machine learning when using Python. Sometimes, developers may be trying to solve a problem where they need to analyze different models of machine learning to achieve better accuracy or any other metric, and then plot their results using different data visualization packages.
In such situations, they can write the same code multiple times, which is often frustrating and time-consuming, or simply create a function with certain parameters for each model and call it whenever needed. Obviously, the last option is more simple and efficient.
In addition, when a dataset contains tons of information and features, the amount of work and effort required will also increase. Therefore, after analyzing and engineering different data and features, developers can easily define a function that combines various tasks or elements and create plots easily and automatically.
Substantially, when developers define a function, they will drastically reduce the complexity and length of their code, as well as the time and resources required to run it efficiently. In other words, it will help them automate the whole process.
Python also allows for a defined function in the program to call itself, also known as function recursion. This programming and mathematical concept allow developers to loop through data to
achieve a specific result. However, they should be cautious with this function because it is possible to code a service that uses too much processing power and memory, or one that never terminates. When done correctly, however, it can be an elegant and efficient approach to programming.
Conditional Statements
The world is a complicated place; therefore, there is no reason why coding should be secure, right? Often, a program needs to choose between different statements, execute certain statements multiple times, or skip over others to complete. This is why there is a need for control structures, which direct or manage the order of statement execution within a program.
To function in the real world, people often have to analyze information or situations and choose the right action to take based on what they observe and understand. In the same way, in Python, conditional statements are the tool developers use to code the decision-making process.
Controlled by IF statements in Python, conditional statements perform various actions and computations depending on whether a particular constraint is true or false. Primarily, a conditional statement works as a decision-making tool and runs the body of code only when it is true. Developers use this statement when they want to justify one of two conditions.
On the other hand, they use the 'else condition, when they need to judge one statement based on another. In other words, if one condition is not real, then there should be a condition justifying this logic. However, sometimes, this condition might not generate the expected results; instead, it gives the wrong result due to an error in the program logic, which often happens when developers need to justify more than two conditions or statements in a program.
In its most basic form, the IF statement looks as follows:
1.
If <expr>:
2.
<statement>
In this case, if the first part of the statement is true, then the second part will execute. On the other hand, if the first one is false, the program will skip the second one or not execute the statement at all. That said, the colon symbol following the first part is necessary. However, unlike most other programming languages, in Python, developers do not need to enclose the first part of the statement in parentheses.
There are situations where a developer may want to evaluate a particular condition and do several things if it proves to be true. For example:
If the sun comes out, I will
:
1. Take a walk
2. Weed the garden
3. Mow the lawn
If the sun does not come out, then I will not perform any of these functions.
In most other programming languages, the developer will group all three statements into one block, and, if the first condition returns true, then the program will execute all three statements in the block. If it returns false, however, none will execute.
Python, on the other hand, follows the offside rule, which is all about indentation. Peter J Landin, a computer scientist from Britain, coined this term taken from the wrong law in soccer. The relatively few machine languages that follow this rule define these compound statements or blocks using indentation.
In Python, indentation plays a vital function, in addition to defining blocks. Python considers contiguous statements indented to the same level to constitute the same compound statement. Therefore, the program executes the whole block if the report returns true, or skips it if false. In Python, a suite is a group of accounts with the same level of indentation level.
Most other machine languages, on the other hand, use unique tokens to identify the beginning and
end of a block, while others use keywords. Beauty, however, is in the eye of the beholder. On the one hand, the use of indentation by Python is consistent, concise, and clean.
On the other hand, in machine languages that do not adhere to the offside rule, code indentation is independent of code function and block definition. Therefore, developers can write indent their code in a way that does not match how it executes, which can create a wrong impression when someone looks at it. In Python, this type of mistake cannot happen. The use of indentation to define compound statements forces developers to remain true to their standards of formatting code.
Sometimes, while evaluating a certain condition, developers might want to perform a certain function if the condition is true, and perform an alternative function if it turns out to be false. This is where the 'else' clause comes in. for example:
- if <expr>:
- <statement/statements>
- else:
- <statement/statements>
If the first line of the statement returns true, the program executes the first statement or group of statements and skips the second condition. On the other hand, if the first condition returns false,
the program skips the first condition and executes the second one. Whatever happens, however, the program resumes after the second set of conditions.
In any case, indentations define both suits of statements. As opposed to machine languages that use delimiters, Python uses indentation; therefore, developers cannot specify an empty block, which is a good thing.
Other types of conditional statements supported by Python that developers need to look into include:
1. Python's ternary operator
2. One line IF statements
3. The PASS statement
4. While statement
5. For statement
Conditional statements are essential when it comes to writing a more complex and powerful Python code. These control statements or structures allow for the facilitation of iteration, which is the execution of a block or single account repeatedly.
Loop
Traditionally, developers used loops when they needed to repeat a block of code a certain number of times. Every vital activity in life needs practice to be perfect. In the same way, machine-learning programs also need repetition to learn, adapt,
and perform the desired functions, which means looping back over the same code or block of law multiple times.
Python supports several ways of executing loops. While all these ways offer the same basic functionality, they are different when it comes to their condition checking time and syntax. The main types of loops in Python are:
- While loop
- For in loop
The first type of loop repeats as long as certain conditions return true. Developers use this loop to execute certain blocks of statements until the program satisfies certain conditions. When this happens, the line or code following the look performs. However, this is a never-ending loop unless forcefully terminated; therefore, developers need to be careful when using it
Fortunately, developers can use a 'break statement' to exit the loop, or a 'continue statement' to skip the current block and return to the original statement. They can also use the 'else' clause if the 'while' or 'for' statement fails.
On the other hand, developers use for loops to traverse an array, string, or list. These loops repeat over a specific sequence of numbers using the 'xrange' or 'range' functions. The difference between these two ranges is that the second one
generates a new series with the same field, while the first one creates an iterator, making it more helpful and efficient.
Other types of loops developers need to look into include:
1. Iterating by the index of elements
2. Using else-statements with for in loops
3. Nested loops
4. Loop control statements
When Guido van Rossum released Python back in 1991, he had no idea that it would come to be one of the most popular and fastest-growing computer learning languages on the market. For many developers, it is the perfect computer language for fast prototyping because of its readability, adaptability, understandability, and flexibility.