Python Programming/Conditions

From Wikiversity
Jump to navigation Jump to search

This lesson introduces conditions and exception handling.

Objectives and Skills[edit | edit source]

Objectives and skills for this lesson include:[1]

  • Control Flow
    • The if statement
  • Exceptions
    • Errors and exceptions
    • Handling and raising Exceptions
    • Try, Finally and the with statement

Readings[edit | edit source]

  1. Wikipedia: Conditional (computer programming)
  2. Wikipedia: Exception handling
  3. Python for Everyone: Conditional execution

Multimedia[edit | edit source]

  1. YouTube: Python Tutorial for Beginners 6: Conditionals and Booleans - If, Else, and Elif Statements
  2. YouTube: Python for Informatics - Chapter 3 - Conditional Execution
  3. YouTube: If, Then, Else in Python
  4. YouTube: Python if elif else
  5. YouTube: How to Use If Else Statements in Python

Examples[edit | edit source]

Comparison Operations[edit | edit source]

There are eight comparison operations in Python.[2]

a = 3
b = 2

print(a == b)       # False
print(a != b)       # True
print(a < b)        # False
print(a > b)        # True
print(a <= b)       # False
print(a >= b)       # True
print(a is b)       # False
print(a is not b)   # True

Boolean Operations[edit | edit source]

The Boolean operations include and, or, and not.[3]

a = 3
b = 2

print(a < b and b < a)    # False
print(a < b or b < a)     # True
print(a < b)              # False
print(not(a < b))         # True

Bitwise Operations[edit | edit source]

Bitwise operations only make sense for integers. Negative numbers are treated as their 2’s complement value.[4]

a = 5
b = 3

print(bin(a))        # 0101
print(bin(b))        # 0011
print(bin(a & b))    # 0001
print(bin(a | b))    # 0111
print(bin(a ^ b))    # 0110
print(bin(~a))       # -0110
print(bin(a << b))   # 101000
print(bin(a >> b))   # 000000

If Statement[edit | edit source]

An if statement may contain zero or more elif parts, and the else part is optional. The keyword ‘elif‘ is short for ‘else if’, and is useful to avoid excessive indentation. An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages.[5]

input = input("Is it morning (m), afternoon (a), or evening (e)? ")
if input == "m":
    print("Good morning!")
elif input == "a":
    print("Good afternoon!")
elif input == "e":
    print("Good evening!")
else:
    print("Hello!")

Try Statement[edit | edit source]

The try statement executes the try clause. If no exception occurs, the except clause is skipped. If an exception occurs during execution of the try clause, the except clause is executed, and then execution continues after the try statement.[6]

try:
    value = input("Enter a numeric value: ")
    result = 1 / float(value)
    print("1 / " + value + " = " + str(result))
except:
    print("An error occurred dividing 1 by " + value + "!")

Except Statement[edit | edit source]

A try statement may have more than one except clause, to specify handlers for different exceptions.[7]

try:
    value = input("Enter a numeric value: ")
    result = 1 / float(value)
    print("1 / " + value + " = " + str(result))
except ValueError as error:
    print(value + " is not a numeric value!")
except ZeroDivisionError as error:
    print("Cannot divide by 0!")
except:
    print("An unexpected error occurred dividing 1 by " + value + "!")

Activities[edit | edit source]

Tutorials[edit | edit source]

  1. Complete one or more of the following tutorials:

Practice[edit | edit source]

  1. Review Python.org: Truth Value Testing. Create a Python program that uses different values and conditions to confirm that in Python zero is false and anything non-zero is true. Also show that the explicit value of False is 0 and the explicit value of True is 1.
  2. Create a Python 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 months, days, hours, or seconds. Use an if/elif/else statement to display their approximate age in the selected timeframe.
  3. Create a Python 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).[8]
  4. Review MathsIsFun: Conversion of Temperature. Create a Python program that asks the user if they would like to convert Fahrenheit to Celsius or Celsius to Fahrenheit. Use an if/elif/else statement to determine their selection and then gather the appropriate input and calculate and display the converted temperature.
  5. Review MathsIsFun: Area of Plane Shapes. Create a Python program that asks the user what shape they would like to calculate the area for. Use an if/elif/else statement to determine their selection and then gather the appropriate input and calculate and display the area of the shape.
  6. Extend one or more of the programs above by adding a try/except block to handle any runtime errors caused by the user entering invalid values for the input.

Games[edit | edit source]

  1. Play CodeCombat.

Lesson Summary[edit | edit source]

Condition Concepts[edit | edit source]

  • 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.[9]
  • The pseudocode structure of a conditional statement is:[10]
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.[11]
  • 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.[12]
  • 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.[13]
  • 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.[14]
  • One mechanism to transfer control, or raise an exception, is known as a throw.[15]
  • The scope for exception handlers starts with a "try" clause.[16]
  • An exception is said to be thrown and execution is transferred to a "catch" or "except" statement.[17][18]

Python Conditions[edit | edit source]

  • The Python syntax for a conditional statement is:[19]
if <condition>:
    <statements>
elif <condition>:
    <statements>
else:
    <statements>
  • An if statement may contain zero or more elif parts, and the else part is optional.[20]
  • An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages.[21]
  • There are eight comparison operations in Python, including ==, !=, <, >, <=, >=, is, is not.[22]
  • There are three Boolean operations in Python, including and, or, not.[23]
  • There are six bitwise operations in Python, including &, |, ^, ~, <<, >>.[24]
  • Bitwise operations only make sense for integers. Negative numbers are treated as their 2’s complement value.[25]
  • The Python syntax for a try statement is:[26]
try:
    <statements>
except <exception>:
    <statements>
except:
    <statements>
  • The try statement executes the try clause. If f no exception occurs, the except clause is skipped. If an exception occurs during execution of the try clause, the except clause is executed, and then execution continues after the try statement.[27]
  • A try statement may have more than one except clause, to specify handlers for different exceptions.[28]

Key Terms[edit | edit source]

body
The sequence of statements within a compound statement.[29]
boolean expression
An expression whose value is either True or False.[30]
branch
One of the alternative sequences of statements in a conditional statement.[31]
chained conditional
A conditional statement with a series of alternative branches.[32]
comparison operator
One of the operators that compares its operands ==, !=, >, <, >=, and <=.[33]
conditional statement
A statement that controls the flow of execution depending on some condition.[34]
condition
The boolean expression in a conditional statement that determines which branch is executed.[35]
compound statement
A statement that consists of a header and a body. The header ends with a colon (). The body is indented relative to the header.[36]
guardian pattern
Where we construct a logical expression with additional comparisons to take advantage of the short-circuit behavior.[37]
logical operator
One of the operators that combines boolean expressions and, or, and not.[38]
nested conditional
A conditional statement that appears in one of the branches of another conditional statement.[39]
traceback
A list of the functions that are executing, printed when an exception occurs.[40]
short circuit
When Python is part-way through evaluating a logical expression and stops the evaluation because Python knows the final value for the expression without needing to evaluate the rest of the expression.[41]

Review Questions[edit | edit source]

Enable JavaScript to hide answers.
Click on a question to see the answer.
  1. Conditional statements are features of a programming language which _____.
    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.
  2. The pseudocode structure of a conditional statement is:
    The pseudocode structure of a conditional statement is:

    IF (boolean condition) THEN
        (consequent)
    ELSE
        (alternative)
    END IF

  3. If a condition is true, _____. Otherwise, the execution continues _____.
    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.
  4. By using ELSE IF/ELSEIF, it is possible to _____.
    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.
  5. Exception handling is the process of _____.
    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.
  6. In programming language mechanisms for exception handling, the term exception is typically used in a specific sense to denote _____.
    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.
  7. One mechanism to transfer control, or raise an exception, is known as _____.
    One mechanism to transfer control, or raise an exception, is known as a throw.
  8. The scope for exception handlers starts with _____.
    The scope for exception handlers starts with a "try" clause.
  9. An exception is said to be thrown and execution is transferred to _____.
    An exception is said to be thrown and execution is transferred to a "catch" or "except" statement.
  10. The Python syntax for a conditional statement is:
    The Python syntax for a conditional statement is:

    if <condition>:
        <statements>
    elif <condition>:
        <statements>
    else:
        <statements>

  11. An if statement may contain zero or more _____ parts, and the _____ part is optional.
    An if statement may contain zero or more elif parts, and the else part is optional.
  12. An if ... elif ... elif ... sequence is a substitute for _____ found in other languages.
    An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages.
  13. There are eight comparison operations in Python, including _____.
    There are eight comparison operations in Python, including ==, !=, <, >, <=, >=, is, is not.
  14. There are three Boolean operations in Python, including _____.
    There are three Boolean operations in Python, including and, or, not.
  15. There are six bitwise operations in Python, including _____.
    There are six bitwise operations in Python, including &, |, ^, ~, <<, >>.
  16. Bitwise operations only make sense for _____. Negative numbers are treated as _____.
    Bitwise operations only make sense for integers. Negative numbers are treated as their 2’s complement value.
  17. The Python syntax for a try statement is:
    The Python syntax for a try statement is:

    try:
        <statements>
    except <exception>:
        <statements>
    except:
        <statements>

  18. The try statement executes _____. If f no exception occurs, _____. If an exception occurs during execution _____.
    The try statement executes the try clause. If f no exception occurs, the except clause is skipped. If an exception occurs during execution of the try clause, the except clause is executed, and then execution continues after the try statement.
  19. A try statement may have more than one _____.
    A try statement may have more than one except clause, to specify handlers for different exceptions.

Assessments[edit | edit source]

See Also[edit | edit source]

References[edit | edit source]

  1. Vskills: Certified Python Developer
  2. Python.org: Built-in Types
  3. Python.org: Built-in Types
  4. Python.org: Built-in Types
  5. Python.org: More Control Flow Tools
  6. Python.org: Errors and Exceptions
  7. Python.org: Errors and Exceptions
  8. PythonLearn: Conditional Execution
  9. Wikipedia: Conditional (computer programming)
  10. Wikipedia: Conditional (computer programming)
  11. Wikipedia: Conditional (computer programming)
  12. Wikipedia: Conditional (computer programming)
  13. Wikipedia: Exception handling
  14. Wikipedia: Exception handling
  15. Wikipedia: Exception handling
  16. Wikipedia: Exception handling
  17. Wikipedia: Exception handling
  18. Python.org Handling Exceptions
  19. Python.org: More Control Flow Tools
  20. Python.org: More Control Flow Tools
  21. Python.org: More Control Flow Tools
  22. Python.org: Built-in Types
  23. Python.org: Built-in Types
  24. Python.org: Built-in Types
  25. Python.org: Built-in Types
  26. Python.org Handling Exceptions
  27. Python.org: Errors and Exceptions
  28. Python.org: Errors and Exceptions
  29. PythonLearn: Conditional execution
  30. PythonLearn: Conditional execution
  31. PythonLearn: Conditional execution
  32. PythonLearn: Conditional execution
  33. PythonLearn: Conditional execution
  34. PythonLearn: Conditional execution
  35. PythonLearn: Conditional execution
  36. PythonLearn: Conditional execution
  37. PythonLearn: Conditional execution
  38. PythonLearn: Conditional execution
  39. PythonLearn: Conditional execution
  40. PythonLearn: Conditional execution
  41. PythonLearn: Conditional execution