# Applied Programming/Conditions
## Structured Programming
### What is it?

Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making extensive use of the structured control flow constructs of selection (if/then/else) and repetition (while and for), block structures, and subroutines. Structured programming is most frequently used with deviations that allow for clearer programs in some particular cases, such as when exception handling has to be performed.

### Control Structures
#### Sequence

Ordered statements or subroutines executed in sequence. It allows us to carry tasks that have multiple steps. In programming, sequence is a basic algorithm: A set of logical steps carried out in order.
Sequence execution of code statements (one line after another) -- like following a recipe
Output:
In the above example, lines of code are executed until the program outputs the sum of x and y.

#### Selection

It's used to make choices depending on information. An algorithm can be made smarter by using IF, THEN, and ELSE functions to reiterate instructions, or to move the process in question to different parts of the program. Selection is also called decision. It is one of the three basic logic assemblies in computer programming. The other two logic assemblies are sequence and loop.
The most common selection statement is the if/else statement. Basic syntax:
The else clause is optional, so this format is also legal:
Output:
In the above example, the user inputs a score and the program outputs a grade based on that score. The if/elif/else structure is used here.

#### Repetition/Iteration

Repetition in a program means that lines of code will be run multiple times.
Iteration is a term similar to repetition: it means to continue repeating an action until you achieve the correct outcome.
Such as:
* while
* do/while
* for
Output:
In the above example, the program prints from 1 to 4. The for structure is used here.
In the above example, the user inputs a score and the program outputs a grade based on that score. The program continues to run as long as the the user enters y to keep going. The program is terminated when the user enters anything else. The while structure is used here.

#### Recursion

Recursion is the process of defining a problem (or the solution to a problem) in terms of (a simpler version of) itself.
Output:
In the above example, the program calculates a factorial by using recursion. When this function is run, an ”if” statement is executed. This statement checks whether the number passed to the function is equal to 1. If it is, our function returns 1. Otherwise, the factorial of our number is calculated. This calculation works by multiplying the number passed to the function by the factorial of the previous number. This function is called again and again until “number” is equal to 1. Each time the function is called, the value of “number” is reduced by 1.

### Subroutines

In structured programming, various functions are declared, defined, and executed. Functions that structure programs are called "subroutines" or "procedures." Subroutines become very handy if they are implemented repeatedly.
Such functions are declared with "def."
Output:
For example, if one wants to execute grading programming, "course_letter_grade" function execute the corresponding letter grade based on the entered score.

### Blocks

Blocks in Python is an indentation. Indentation determines the scope of conditional statements. The indentation level constrains each block.
Output:
Block 1 serves as an initiation of operation or an opening code for the "course_score" operation. Block 2s are served to determine and to select appropriate Block3 based on the input in Block1. Block 3s are served to show the result of Block 2.

### Why use this?

Below lists some advantages and disadvantages to using structured programming.

#### Advantages

* Easier to read and understand
* User Friendly
* Easier to Maintain
* Mainly problem based instead of being machine based
* Development is easier as it requires less effort and time
* Easier to Debug
* Machine-Independent, mostly.

#### Disadvantages

* Being Machine-Independent, it takes time to convert into machine code.
* The converted machine code is not the same as for assembly language.
* The program depends upon changeable factors like data-types. Therefore it needs to be updated with the need on the go.
* Usually the development in this approach takes longer time as it is language-dependent. Whereas in the case of assembly language, the development takes lesser time as it is fixed for the machine.

## Data validation

In computer science, data validation is the process of ensuring data has undergone data cleansing to ensure they have, that is, that they are both correct and useful. It uses routines, often called "validation rules", "validation constraints", or "check routines", that check for correctness, meaningfulness, and security of data that are input to the system. The rules may be implemented through the automated facilities of a data dictionary, or by the inclusion of explicit application program validation logic of the computer and its application.

### Validation in Python

Whenever an input is accepted by the user, it needs to be checked for validation which checks if the input data is what we are expecting and the validation can be done in two different ways, that is by using a flag variable or by using try or except which the flag variable will be set to false initially and if we can find out that the input data is what we are expecting the flag status can be set to true and find out what can be done next based on the status of the flag whereas while using try or except, a section of code is tried to run and if there is a negative response, then the except block of code is run.

### Types of Validation in Python

There are three types of validation in python, they are:
Type Check: This validation technique in python is used to check the data type of the given input. For example, int, float, etc. Length Check: This validation technique in python is used to check the length of the given input string. Range Check: This validation technique in python is used to check if a given number falls in between the two numbers. The syntax for validation in Python is given below:
Syntax using flag:
The status of the flag is set to false initially and the same condition is considered for a while loop to make the statement while not true, and the validation is performed setting the flag to true if the validation condition is satisfied otherwise the error message is printed.
Syntax using an exception:
We set the condition to be true initially and perform the necessary validation by running a block of code and if the code fails to perform the validation, an exception is raised displaying the error message and a success message is printed if the code is successfully executed by the try block.
Examples of Python validation are:
Example 1 Python program using a flag to validate if the input given by the user is an integer.#Datatype check.
Output:
Example 2 Python program using flag and exception to validate the type of input given by the user and to determine if it lies within a given range.
Output:
Example 3 Python program using flag to check the length of the input string. #Length Check.
Output:
Benefits
* It helps to improve the security of code.
* Validation in python prevents third-party users from mishandling the code accidentally or intentionally.
* It can be used to check if the input data type is correct or not.
* It can be used to check if there are no invalid values in the given input.
* It can be used to check if the given input lies in the range or is it out of range.
* It can be used to check if the given input meets the constraints specified on them.
* It can be used to check if the given input is consistent or not.
* Validation in python can be used to check if the given input is valid.
* Validation in python can be used to check if the given input is complete or incomplete.

## Exception Handling

In computing and computer programming, exception handling is the process of responding to the occurrence of exceptions – anomalous or exceptional conditions requiring special processing - during the execution of a program. In general, an exception breaks the normal flow of execution and executes a pre-registered exception handler; the details of how this is done depend on whether it is a hardware or software exception and how the software exception is implemented. It is provided by specialized programming language constructs, hardware mechanisms like interrupts, or operating system (OS) inter-process communication (IPC) facilities like signals. Some exceptions, especially hardware ones, may be handled so gracefully that execution can resume where it was interrupted.
An alternative approach to exception handling in software is error checking, which maintains normal program flow with later explicit checks for contingencies reported using special return values, an auxiliary global variable such as C's errno, or floating point status flags. Input validation, which preemptively filters exceptional cases, is also an approach.

## Python syntax and semantics/exceptions - EAFP vs. LBYL

The syntax of the Python programming language is the set of rules that defines how a Python program will be written and interpreted (by both the runtime system and by human readers). The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages.

## Defensive programming

Defensive programming is a form of defensive design intended to ensure the continuing function of a piece of software under unforeseen circumstances. Defensive programming practices are often used where high availability, safety, or security is needed. Essentially, defensive programming is a programming style to ensure your program functions as intended no matter the circumstances. Below are a few of the most popular and powerful techniques that can be applied when taking a defensive approach to programming.

### Assertions

An assertion is a boolean expression at a specific point in a program which will be true unless there is a bug in the program. An assertion could simply be a comment used by the programmer to think about how the code works. Or an assertion could document a constraint on the system.
The code above shows a function with an argument declared "age". Within the function, we assert that the age variable must be greater than 18. If we pass any integer 19 or greater through the function, we are met with a response: "You are over 18". However, if we pass an integer of 18 or lower, our program throws an assertion error and crashes.

### Intelligent source code reuse

Intelligent source code reuse is the practice of using previously tested blocks of code as opposed to typing everything up from scratch. If existing code is tested and known to work, reusing it may reduce the chance of bugs being introduced. However, reusing code is not always a good practice, because it also amplifies the damages of a potential attack on the initial code.

### Design by contract

Design by contract (DbC), also known as contract programming, programming by contract and design-by-contract programming, is an approach for designing software.
It prescribes that software designers should define formal, precise and verifiable interface specifications for software components, which extend the ordinary definition of abstract data types with preconditions, postconditions and invariants. These specifications are referred to as "contracts", in accordance with a conceptual metaphor with the conditions and obligations of business contracts.
The DbC approach assumes all client components that invoke an operation on a server component will meet the preconditions specified as required for that operation.
Where this assumption is considered too risky (as in multi-channel or distributed computing), the inverse approach is taken, meaning that the server component tests that all relevant preconditions hold true (before, or while, processing the client component's request) and replies with a suitable error message if not.

### Exception handling

In computing and computer programming, exception handling is the process of responding to the occurrence of exceptions – anomalous or exceptional conditions requiring special processing - during the execution of a program. In general, an exception breaks the normal flow of execution and executes a pre-registered exception handler; the details of how this is done depend on whether it is a hardware or software exception and how the software exception is implemented. Take a look at the code below.
When we run this code, we assume the user will be inputting their age in numbers. However, if the user enters an invalid input, an exception is thrown. Below is the exception thrown when a user enters a letter instead of a number.
Exceptions are typically multiple lines which can be difficult to decipher. One way to solve this issue would be to use a "try-except". In this case, we will be excepting a "ValueError" in the event that the user enters an invalid character.
Now when we run the program and input invalid information, we are met with a message that is much more decipherable.

## Key Terms

Assertion - An assertion is a predicate connected to a point in the program, that always should evaluate to true at that point in code execution. Assertions can help a programmer read the code, help a compiler compile it, or help the program detect its own defects.
Boolean Expression - An expression in a programming language that produces a Boolean value when evaluated, i.e. one of true or false.
Conditional Statements - Allow for selection between alternatives at runtime.
Data Validation - The process of ensuring that data have undergone data cleansing to ensure they have data quality, that is, that they are both correct and useful.
Defensive Programming - A form of defensive design intended to ensure the continuing function of a piece of software under unforeseen circumstances.
EAFP (Easier to Ask Forgiveness than Permission) - Approach that first attempts the desired action then handles any resulting exceptions.
Exception Handling - The process of responding to the occurrence, during computation, of exceptions. Anomalous or exceptional conditions requiring special processing, often changing the normal flow of program execution.
GoTo Statement - Performs a one-way transfer of control to another line of code; in contrast, a function call normally returns control.
If Statement - An if statement is a programming conditional statement that, if proved true, performs a function or displays information.
LBYL (Look Before You Leap) - Approach which a precondition is tested before accessing the sought-after resource.
Logic Error - Error that makes the program deliver unexpected results without crashing it.
Relational Operator - A programming language construct or operator that tests or defines some kind of relation between two entities, including numerical equality (e.g., 5 = 5) and inequalities (e.g., 4 ≥ 3).
Runtime Error - Error produced by the runtime system if something goes wrong while a syntactically correct program is running.
Software Bug - An error, flaw, failure or fault in a computer program or system that causes it to produce an incorrect or unexpected result, or to behave in unintended ways.
Structured Programming - A programming paradigm aimed at improving the clarity, quality, and development time of a computer program.
Syntax - Syntax of a computer language is the set of rules that defines the combinations of symbols that are considered to be a correctly structured document or fragment in that language.
Syntax error - Error that indicates something is wrong with program syntax. It's produced by Python during the translation of the source code into byte code.
Truth Table - A mathematical table used in logic, truth tables can be used to show whether a propositional expression is true for all legitimate input values, that is, logically valid.
Objects - A combination of related variables, constants and other data structures which can be selected and manipulated together.
Conditionals - Help the code make a choice and result in either TRUE or FALSE. These perform different actions depending on the need of the programmer, and multiple conditions can be combined into a single condition, as long as the final value of the condition is either TRUE or FALSE. Examples of conditional statements are ‘IF’, ‘IF-Else’, ‘While’ and ‘Else-If’.
Validation - An automatic computer check to ensure that the data entered is sensible and reasonable. It does not check the accuracy of data

## References

* ↑ Structured Programming
* ↑ http://support.kodable.com/en/articles/417330-what-is-sequence#:~:text=In%20programming%2C%20sequence%20is%20a,order%20of%20steps%2C%20or%20sequence.
* ↑ https://www.cs.fsu.edu/~myers/c++/notes/control1.html
* ↑ https://teachcomputerscience.com/selection/#:~:text=A%20selection%20is%20used%20to,is%20also%20called%20a%20decision.
* ↑ http://facweb.cs.depaul.edu/sjost/it211/documents/structured.htm
* ↑ https://www.bbc.co.uk/bitesize/guides/zcg9kqt/revision/7#:~:text=Repetition%20in%20a%20program%20means,you%20achieve%20the%20correct%20outcome.
* ↑ https://www.cs.fsu.edu/~myers/c++/notes/control1.html
* ↑ http://ww2.cs.fsu.edu/~nienaber/teaching/python/lectures/control-repetition.html
* ↑ https://www.cs.utah.edu/~germain/PPS/Topics/recursion.html
* ↑ https://careerkarma.com/blog/python-recursion/
* ↑ https://www.python-course.eu/functions.php#:~:text=They%20are%20known%20in%20most,defined%20by%20a%20def%20statement./
* ↑ https://www.python-course.eu/python3_blocks.php#:~:text=A%20language%20which%20allows%20grouping,if%20they%20were%20one%20statement./
* ↑ https://www.geeksforgeeks.org/structured-programming-approach-with-advantages-and-disadvantages/
* ↑ https://www.educba.com/python-validation/
* ↑ Defensive_programming
* ↑ https://wiki.c2.com/?WhatAreAssertions
* ↑ Defensive_programming
* ↑ Design_by_contract
* ↑ Exception_handling