# 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. [1]

### 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.[2]

Sequence execution of code statements (one line after another) -- like following a recipe [3]

```x = 33
y = 55
z = x + y
print(z)
```

Output:

```88
```

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.[4]

The most common selection statement is the if/else statement. Basic syntax:

```  if (expression)
statement
else
statement
```

The else clause is optional, so this format is also legal:

```  if (expression)
statement [5]```
```course_score = int(input("Enter a course score: "))

if course_score >= 90:

elif 80 <= course_score < 90:

elif 70 <= course_score < 80:

elif 60 <= course_score < 70:

else:
```

Output:

```Enter a course score: 50
```

In the above example[6], 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.[7]

Such as:

```   -while
-do/while
-for[8]```
```for num in range(1, 5):
print(num)
```

Output:

```1
2
3
4
```

In the above example[9], the program prints from 1 to 4. The for structure is used here.

```keep_going = 'y'

while keep_going == 'y':
course_score = int(input("Enter a course score: "))

if course_score >= 90:

elif 80 <= course_score < 90:

elif 70 <= course_score < 80:

elif 60 <= course_score < 70:

else:

keep_going = input("Do you want to keep going? "
+ "Enter y for yes. ")
```

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.[10]

```def factorial(number):
if number == 1:
return 1
else:
return (number * factorial(number - 1))

```

Output:

```24
```

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.[11]

### 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.[12]

Such functions are declared with "def."

```def course_letter_Grade (course_score):
course_score = int(input("Enter a course score: "))

if course_score >= 90:

elif 80 <= course_score < 90:

elif 70 <= course_score < 80:

elif 60 <= course_score < 70:

else:
```

Output:

```Enter a course score: 50
```

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.[13]

```   course_score = int(input("Enter a course score: "))    #Block 1; intake a course score

if course_score >= 90:                               #Block 2; selects course score
print("Your course grade is A.")                  #Block 3; displays result of the selection

elif 80 <= course_score < 90:                        #Block 2; selects course score
print("Your course grade is B.")                   #Block 3; displays results of the selection

elif 70 <= course_score < 80:                        #Block 2; selects course score
print("Your course grade is C.")                   #Block 3; displays results of the selection

elif 60 <= course_score < 70:                        #Block 2; selection course score
print("Your course grade is D.")                   #Block 3; displays results of the selection

else:                                                #Block 2; selection course score
print("Your course grade is F.")                   #Block 3; displays results of the selection
```

Output:

```Enter a course score: 50
```

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.[14]

• 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.

• Since it is Machine-Independent, So 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:

```    flagName = False
while not flagName:
if [Do check here]:
flagName = True
else:
print('error message')
```

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:

```    while True:
try:
[run code that might fail here] break
except:
print('This is the error message if the code fails')
```
```    print(‘run the code from here if code is successfully run in the try block of code above’)
```

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.

```    #Declare a variable validInt which is also considered as flag and set it to false
validInt = False
#Consider the while condition to be true and prompt the user to enter the input
while not validInt:
#The user is prompted to enter the input
age1 = input('Please enter your age ')
#The input entered by the user is checked to see if it’s a digit or a number
if age1.isdigit():
validInt = True
else:
print('The input is not a valid number')
#This statement is printed if the input entered by the user is a number
print('The entered input is a number and that is ' + str(age1))
```

Output:

```    Please enter your age: 22
The entered input is a number that is 22
```

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.

```    #Range Check.
```
```    #Declare a variable areTeenager which is also considered as flag and set it to false
areTeenager = False
#Consider the while condition to be true and prompt the user to enter the input
while not areTeenager:
try:
#The user is prompted to enter the input
age1 = int(input('Please enter your age '))
#The input entered by the user is checked if it lies between the range specified
if age1 >= 13 and age1 <= 19:
areTeenager = True
except:
print('The age entered by you is not a valid number between 13 and 19')
#This statement is printed if the input entered by the user lies between the range of the number specified
print('You are a teenager whose age is between 13 and 19, and the entered age is  ' + str(age1))
```

Output:

```    Please enter your age: 14
You are a teenager whose age is between 13 and 19, and the entered age is 14
```

Example 3 Python program using flag to check the length of the input string. #Length Check.

```    #Declare a variable lenstring which is also considered as flag and set it to false
lenstring = False
#Consider the while condition to be true and prompt the user to enter the input
while not lenstring:
password1 = input('Please enter a password consisting of five characters ')
#The input entered by the user is checked for its length and if it is below five
if len(password1) >= 5:
lenstring = True
else:
print('The number of characters in the entered password is less than five characters')
#This statement is printed if the input entered by the user consists of less than five characters
print('The entered password is: ' + password1)
```

Output:

```    Please enter a password consisting of at least five characters sdsdsds
The entered password is sdsdsds
```

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.

[15]

## 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.[16] 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.[17]

```   def my_function(age):
assert int(age) > 18
print("You are over 18.")
```

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.[18]

### 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.[19]

### 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.[20] Take a look at the code below.

```   age = int(input("How old are you?"))
new_age = age + 10
print(f"In 10 years, you will be {new_age}!")
```

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.

```   How old are you?
>g

Traceback (most recent call last):
File "C:/Users/Sam/Pycharm/test.py", line 1, in <module>
age = int(input("How old are you?"))
ValueError: invalid literal for int() with base 10: 'g
```

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.

```   try:
age = int(input("How old are you?"))
new_age = age + 10
print(f"In 10 years, you will be {new_age}!")
except ValueError:
print("Invalid input!")
```

Now when we run the program and input invalid information, we are met with a message that is much more decipherable.

```   How old are you?
>g

Invalid input!
```

## 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