Applied Programming/Conditions
Structured Programming
editWhat is it?
editStructured 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
editSequence
editOrdered 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
editIt'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 <ref>https://www.cs.fsu.edu/~myers/c++/notes/control1.html</ref>
course_score = int(input("Enter a course score: "))
if course_score >= 90:
print("Your course grade is A.")
elif 80 <= course_score < 90:
print("Your course grade is B.")
elif 70 <= course_score < 80:
print("Your course grade is C.")
elif 60 <= course_score < 70:
print("Your course grade is D.")
else:
print("Your course grade is F.")
Output:
Enter a course score: 50 Your course grade is F.
In the above example[5], 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
editRepetition 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.[6]
Such as:
- while
- do/while
- for[7]
for num in range(1, 5):
print(num)
Output:
1 2 3 4
In the above example,[8] 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:
print("Your course grade is A.")
elif 80 <= course_score < 90:
print("Your course grade is B.")
elif 70 <= course_score < 80:
print("Your course grade is C.")
elif 60 <= course_score < 70:
print("Your course grade is D.")
else:
print("Your course grade is F.")
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
editRecursion is the process of defining a problem (or the solution to a problem) in terms of (a simpler version of) itself.[9]
def factorial(number):
if number == 1:
return 1
else:
return (number * factorial(number - 1))
answer = factorial(4)
print(answer)
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.[10]
Subroutines
editIn 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.[11]
Such functions are declared with "def."
def course_letter_Grade (course_score):
course_score = int(input("Enter a course score: "))
if course_score >= 90:
print("Your course grade is A.")
elif 80 <= course_score < 90:
print("Your course grade is B.")
elif 70 <= course_score < 80:
print("Your course grade is C.")
elif 60 <= course_score < 70:
print("Your course grade is D.")
else:
print("Your course grade is F.")
Output:
Enter a course score: 50 Your course grade is F.
For example, if one wants to execute grading programming, "course_letter_grade" function execute the corresponding letter grade based on the entered score.
Blocks
editBlocks in Python is an indentation. Indentation determines the scope of conditional statements. The indentation level constrains each block.[12]
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 Your course grade is F.
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?
editBelow lists some advantages and disadvantages to using structured programming.[13]
Advantages
edit- 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
edit- 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
editIn 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
editWhenever 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
editThere 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.
Exception Handling
editIn 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
editThe 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
editDefensive 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.[15] 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
editAn 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.[16]
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
editIntelligent 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.[17]
Design by contract
editDesign 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.[18]
Exception handling
editIn 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.[19] 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
editAssertion - 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
edit- ↑ 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