Lecture-10_Selection Python_24-25
COMP101 Introduction to Programming 2024-25
Lecture-10: Selection in Python
Terminology
Python selection syntax uses three commands:
if:
elif:
else:
Important notes:
A colon (
:) must followif,elif, andelse.All code after the colon must be indented.
Default indentation is 4 spaces; changing this can create confusion.
Unlike other languages, Python does not use:
thencaseorswitch{ }delimiters
Selection Syntax
Standard structure:
if-elif-elseUsually contains one
ifat the start and oneelseat the end.Multiple
elifstatements can be included as necessary.
Tests return a boolean value (True or False).
Supported operators in tests:
Comparison Operators: <, >=, <=, >, !=, ==
Boolean Operators: and, or, not
breakandcontinueare used specifically for iteration.
If Statement Mechanics
Example usage with dice roll:
Accept user input:
number = int(input(\"Enter a throw of a die, 1 to 6: \\"))The structure follows:
If the number is 6:
if (number == 6): print(\"Throw again\")Continuation:
Ends with a sequence statement (left-aligned):
print(\"End of game\")
Note: The if-statement must evaluate True or False; binary operators assist in this.
If Statement Examples
If the condition is true, all indented lines execute:
if (num > 0): print(\"Test is True. Number is positive\")If false, all indented code is ignored.
if ... else Structure
Align
elsewithif, ensure the colon followselse:if (num > 0): print(\"Test is True. Number is positive\") else: print(\"Test is False. Number is negative\")
Handling Logical Errors
For erroneous input (0):
If
(num > 0)evaluates to False, else code executes.Address any logical inaccuracies:
Modify the condition to
num >= 0to include zero as a valid input.
Two solutions discussed:
Modify the boolean test
Introduce
elifto create stronger logic.
Utilizing elif
elifstatements enable additional checks betweenifandelse, requiring a unique test condition.Proper structure:
if (test): # block elif (another_test): # block else: # block
Structuring the Selection Statement
Ensure to stick with the single
ifat the beginning and a singleelseat the end, with zero or moreelifclauses in between.Good programming practices:
Effective use of if - elif - else enhances robustness by validating multiple conditions.
Summary Points
Understand how each block executes based on the test value.
Keep your input and conditions clear to avoid confusion.
A comprehensive structure enhances logic and verification in programming.
Handling Errors and Debugging
Maintain proper syntax and test conditions.
Review and differentiate between expected output and logical accuracy.
Good practices ensure smooth execution and fewer runtime errors in Python programs.