Python Programming/Conditions
This lesson introduces conditions and exception handling.
Objectives and Skills
editObjectives 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
editMultimedia
editExamples
editComparison Operations
editThere 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
editThe 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
editBitwise 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
editAn 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
editThe 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
editA 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
editTutorials
edit- Complete one or more of the following tutorials:
- LearnPython
- TutorialsPoint
- Codecademy
- Wikiversity
- Wikibooks
Practice
edit- 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.
- 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.
- 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]
- 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.
- 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.
- 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- Play CodeCombat.
Lesson Summary
editCondition Concepts
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.[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 theELSE
block (which is usually optional), or if there is noELSE
branch, then after theEND 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- 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- 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-
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.
-
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 -
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.
-
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.
-
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.
-
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.
-
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.
-
The scope for exception handlers starts with _____.The scope for exception handlers starts with a "try" clause.
-
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.
-
The Python syntax for a conditional statement is:The Python syntax for a conditional statement is:
if <condition>:
<statements>
elif <condition>:
<statements>
else:
<statements> -
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.
-
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.
-
There are eight comparison operations in Python, including _____.There are eight comparison operations in Python, including ==, !=, <, >, <=, >=, is, is not.
-
There are three Boolean operations in Python, including _____.There are three Boolean operations in Python, including and, or, not.
-
There are six bitwise operations in Python, including _____.There are six bitwise operations in Python, including &, |, ^, ~, <<, >>.
-
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.
-
The Python syntax for a try statement is:The Python syntax for a try statement is:
try:
<statements>
except <exception>:
<statements>
except:
<statements> -
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.
-
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
editSee Also
edit- Python.org: More Control Flow Tools
- Python.org: Errors and Exceptions
- Python.org: Compound statements
- Real Python: Python Conditional Statements
- Open Book Project: Python 3 - Conditionals
- TutorialsPoint: Python If...Elif...Else Statements
- PYDanny: Why Doesn't Python Have Switch Case?
- Flocabulary.com: Conditionals
References
edit- ↑ Vskills: Certified Python Developer
- ↑ Python.org: Built-in Types
- ↑ Python.org: Built-in Types
- ↑ Python.org: Built-in Types
- ↑ Python.org: More Control Flow Tools
- ↑ Python.org: Errors and Exceptions
- ↑ Python.org: Errors and Exceptions
- ↑ PythonLearn: Conditional Execution
- ↑ Wikipedia: Conditional (computer programming)
- ↑ Wikipedia: Conditional (computer programming)
- ↑ Wikipedia: Conditional (computer programming)
- ↑ Wikipedia: Conditional (computer programming)
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Python.org Handling Exceptions
- ↑ Python.org: More Control Flow Tools
- ↑ Python.org: More Control Flow Tools
- ↑ Python.org: More Control Flow Tools
- ↑ Python.org: Built-in Types
- ↑ Python.org: Built-in Types
- ↑ Python.org: Built-in Types
- ↑ Python.org: Built-in Types
- ↑ Python.org Handling Exceptions
- ↑ Python.org: Errors and Exceptions
- ↑ Python.org: Errors and Exceptions
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution