Programming Fundamentals/Conditions

From Wikiversity
Jump to navigation Jump to search
Flowchart Conditions

This lesson introduces conditions, including if-then-else, case/switch, and structured exception handling.

Objectives and Skills[edit]

Objectives and skills for this lesson include:

  • Understand structured programming concepts
  • Understand sequence, selection/condition, and iteration/loop control structures
  • Understand if-then-else and case/switch statements
  • Understand structured exception handling concepts
  • Use conditional code to implement program functionality

Readings[edit]

  1. Rebus: Programming Fundamentals
  2. Wikipedia: Structured programming
  3. Wikipedia: Conditional (computer programming)
  4. Wikipedia: Exception handling

Multimedia[edit]

  1. YouTube: The three basic structures—sequence, selection, and loop
  2. YouTube: Programming For Beginners - Relational Operators
  3. YouTube: Introduction to Programming - Control Flow

Examples[edit]

Activities[edit]

Complete the following activities using pseudocode, a flowcharting tool, or your selected programming language. Use separate functions for input, each type of processing, and output. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

  1. Create a program to prompt the user for hours and rate per hour to compute gross pay (hours * rate). Include a calculation to give 1.5 times the hourly rate for any overtime (hours worked above 40 hours).[1]
  2. Create a program that asks the user how old they are in years. Then ask the user if they would like to know how old they are in (M)onths, (D)ays, (H)ours, or (S)econds. Use if/else conditional statements to display their approximate age in the selected timeframe. Do not perform any unnecessary calculations.
  3. Review MathsIsFun: US Standard Lengths. Create a program that asks the user for a distance in miles, and then ask the user if they want the distance in US measurements (yards, feet, and inches) or in metric measurements (kilometers, meters, and centimeters). Use if/else conditional statements to determine their selection and then calculate and display the results.
  4. Review MathsIsFun: Area of Plane Shapes. Create a program that asks the user what shape they would like to calculate the area for. Use if/else conditional statements to determine their selection and then gather the appropriate input and calculate and display the area of the shape.
  5. Create a program that helps the user determine what sock size to order based on their shoe size:
        < 4 = extra small
        4 to 6 = small
        7 to 9 = medium
        10 to 12 = large
        13+ = extra large
    Use if/else conditional statements to determine their selection and then display the results. Round half-sizes up to the next whole size. One option for rounding is to add 0.5 and then convert to an integer.[2]
  6. If your programming language supports it, update one or more of the programs above to replace the if/else conditional statements with case/select conditional statements.
  7. Review Wikipedia: Is functions. If your programming language supports it, update one or more of the programs above to include input validation for all numeric input.
  8. If your programming language supports it, extend one or more of the programs above by adding structured exception handling statements (try-catch, try-except, etc.) to handle any runtime errors caused by the user entering invalid values for the input.

Lesson Summary[edit]

  • Conditional statements are features of a programming language which perform different computations or actions depending on whether a programmer-specified Boolean condition evaluates to true or false.[3] The basic attribute of a selection control structure is to select between two or more alternative paths. A question using Boolean logic controls which path is selected.[4]
  • The pseudocode structure of a conditional statement is:[5]
IF (Boolean condition) THEN
    (consequent)
ELSE
    (alternative)
END IF
  • If the condition is true, the statements following the THEN are executed. Otherwise, the execution continues in the following branch – either in the ELSE block (which is usually optional), or if there is no ELSE branch, then after the END IF.[6]
  • By using ELSE IF/ELSEIF, it is possible to combine several conditions. Only the statements following the first condition that is found to be true will be executed. All other statements will be skipped.[7]
  • Exception handling is the process of responding to the occurrence, during computation, of anomalous or exceptional events requiring special processing, often changing the normal flow of program execution.[8]
  • In programming language mechanisms for exception handling, the term exception is typically used in a specific sense to denote a data structure storing information about an exceptional condition.[9]
  • One mechanism to transfer control, or raise an exception, is known as a throw.[10]
  • The scope for exception handlers starts with a "try" clause.[11]
  • An exception is said to be thrown and execution is transferred to a "catch" or "except" statement.[12][13]
  • Operator symbols and/or names can vary with different programming languages. Most programming languages use relational operators similar to the following:[14]
Operator	Meaning
<	        less than
>	        greater than
<=	        less than or equal to
>=	        greater than or equal to
==	        equality (equal to)
!= or <>	inequality (not equal to)
Please, be careful as in many programming languages the ≠ is not used and the = symbol means assignment. [15]
  • Two-way selection structures may be nested inside other two-way selection structures, resulting in multi-way selection. The concept of nesting allows the mixing of the different categories of control structures.[16]
  • One of the most important concepts of programming is the ability to control a program so that different lines of code are executed or that some lines of code are executed many times. The mechanisms that allow us to control the flow of execution are called control structures.[17]
  • It is possible to establish more than one condition in one IF by using logical operators (AND, OR and NOT), these operations are used to make more open or strict decisions, depending on the programmer's needs.[source?]

Key Terms[edit]

Boolean expression
A logical statement that is either "True" or "False". It is used to compare 2 variables as long as they are the same data type.[18]
branching
An instruction in a computer program that can cause a computer to begin executing a different instruction sequence. This causes the program to deviate from its default behavior of executing instructions in order. This behavior is undesirable, and is therefore rarely used in modular structured programming.[19]
code block
In computer programming, a block or code block is a lexical structure of source code which is grouped together. Blocks consist of one or more declarations and statements. Depending on the programming language, a code block can be signified by curly brackets "{}" or indentation.[20]
control structures
The mechanisms used to control the code's flow of execution.[21]
if then else
A two-way selection control structure. Questions with a Boolean true or false answer controls what the structure does. Simply put, the "if" part of the structure will do something if the question's answer is true, while the "else" part of the statement will do something if the question's answer is false.[22]
multiway selection
Using control structures to be able to select from more than two choices. Nested control structures Placing one control structure inside of another.[23]
logical operator
A logical operator is a symbol or word used to connect two or more expressions such that the value of the compound expression produced depends only on that of the original expressions and on the meaning of the operator. Common logical operators include AND, OR, and NOT. Python just uses the words and, or, and not. In many other languages && is used for AND, || is used for OR, and ! is used for not.[source?]
relational operator
An operator that defines or tests a relationship between 2 variables. They consist of: less than, less than or equal to, equal to, not equal to, more than, more than or equal to.[24]
selection
A control structure where the program chooses between two or more options.[25]
sequence
A control structure where the program executes the items in the order listed.[26]
spaghetti code
A pejorative phrase for unstructured and difficult-to-maintain source code. Spaghetti code can be caused by several factors, such as volatile project requirements, lack of programming style rules, and insufficient ability or experience.[27]
structured programming
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. Thus, preventing Spaghetti code as a result.[28]
truth table
A table used to test Boolean logic. The table compares different combinations of a function's input values. It is also a common way to show logical relationships.[29]

Assessments[edit]

See Also[edit]

References[edit]

  1. PythonLearn: Conditional Execution
  2. Wikibooks: Programming Fundamentals/Practice: Conditions
  3. Wikipedia: Conditional (computer programming)
  4. Programing Fundamentals (Kenneth Leroy Busbee and Dave Braunschweig)
  5. Wikipedia: Conditional (computer programming)
  6. Wikipedia: Conditional (computer programming)
  7. Wikipedia: Conditional (computer programming)
  8. Wikipedia: Exception handling
  9. Wikipedia: Exception handling
  10. Wikipedia: Exception handling
  11. Wikipedia: Exception handling
  12. Wikipedia: Exception handling
  13. Python.org Handling Exceptions
  14. https://press.rebus.community/programmingfundamentals/chapter/relational-operators/
  15. Programing Fundamentals (Kenneth Leroy Busbee and Dave Braunschweigh)
  16. Programing Fundamentals (Kenneth Leroy Busbee and Dave Braunschweigh)
  17. https://press.rebus.community/programmingfundamentals/chapter/structured-programming/
  18. Wikipedia: Boolean expression
  19. Wikipedia: Branch (computer science)
  20. Wikipedia: Block (programming)
  21. [[1]]
  22. https://press.rebus.community/programmingfundamentals/chapter/if-then-else/
  23. https://press.rebus.community/programmingfundamentals/chapter/nested-if-then-else/
  24. Wikipedia: Relational operator
  25. https://press.rebus.community/programmingfundamentals/chapter/structured-programming/
  26. https://press.rebus.community/programmingfundamentals/chapter/structured-programming/
  27. Wikipedia: Spaghetti code
  28. Wikipedia: Structured programming
  29. Wikipedia: Truth table