0% found this document useful (0 votes)
17 views30 pages

Python Conditional Execution Guide

Chapter 3 of 'Python for Everybody' covers conditional execution using comparison operators, indentation rules, and decision-making structures such as one-way, two-way, and multi-way decisions. It explains the use of logical operators and the try/except structure for error handling in Python. Additionally, exercises are provided to reinforce the concepts of pay computation and handling non-numeric input.

Uploaded by

danglyquan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views30 pages

Python Conditional Execution Guide

Chapter 3 of 'Python for Everybody' covers conditional execution using comparison operators, indentation rules, and decision-making structures such as one-way, two-way, and multi-way decisions. It explains the use of logical operators and the try/except structure for error handling in Python. Additionally, exercises are provided to reinforce the concepts of pay computation and handling non-numeric input.

Uploaded by

danglyquan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Conditional Execution

Chapter 3

Python for Everybody


[Link]
Comparison Operators
• Boolean expressions ask a Python Meaning
question and produce a Yes or No < Less than
result which we use to control
program flow <= Less than or Equal to
== Equal to
• Boolean expressions using >= Greater than or Equal to
comparison operators evaluate to
> Greater than
True / False or Yes / No
!= Not equal
• Comparison operators look at
variables but do not change the Remember: “=” is used for assignment.
variables
[Link]
Comparison Operators
x=5
Conditional Steps
Yes
x < 10 ?

No print('Smaller') Program:
Output:
x = 5
Yes if x < 10: Smaller
x > 20 ? print('Smaller') Finish
if x > 20:
No print('Bigger') print('Bigger')

print('Finish')

print('Finish')
Comparison Operators
x = 5
if x == 5 :
print('Equals 5') Equals 5
if x > 4 :
print('Greater than 4')
Greater than 4
if x >= 5 : Greater than or Equals 5
print('Greater than or Equals 5')
if x < 6 : print('Less than 6') Less than 6
if x <= 5 :
print('Less than or Equals 5') Less than or Equals 5
if x != 6 :
print('Not equal 6') Not equal 6
Indentation
• Increase indent indent after an if statement or for statement (after : )

• Maintain indent to indicate the scope of the block (which lines are affected
by the if/for)

• Reduce indent back to the level of the if statement or for statement to


indicate the end of the block

• Blank lines are ignored - they do not affect indentation

• Comments on a line by themselves are ignored with regard to indentation


One-Way Decisions
x = 5 Yes
print('Before 5') Before 5 x == 5 ?
if x == 5 :
print('Is 5') Is 5 print('Is 5’)
No
print('Is Still 5')
Is Still 5
print('Third 5')
print('Afterwards 5')
Third 5 print('Still 5')
print('Before 6') Afterwards 5
if x == 6 : Before 6 print('Third 5')
print('Is 6')
print('Is Still 6')
print('Third 6')
print('Afterwards 6') Afterwards 6
Warning: Turn Off Tabs!!
• Atom automatically uses spaces for files with ".py" extension (nice!)

• Most text editors can turn tabs into spaces - make sure to enable this
feature

- NotePad++: Settings -> Preferences -> Language Menu/Tab Settings

- TextWrangler: TextWrangler -> Preferences -> Editor Defaults

• Python cares a *lot* about how far a line is indented. If you mix tabs and
spaces, you may get “indentation errors” even if everything looks fine
increase / maintain after if or for
decrease to indicate end of block
x = 5
if x > 2 :
print('Bigger than 2')
print('Still bigger')
print('Done with 2')

for i in range(5) :
print(i)
if i > 2 :
print('Bigger than 2')
print('Done with i', i)
print('All Done')
Think About begin/end Blocks
x = 5
if x > 2 :
print('Bigger than 2')
print('Still bigger')
print('Done with 2')

for i in range(5) :
print(i)
if i > 2 :
print('Bigger than 2')
print('Done with i', i)
print('All Done')
Nested x>1
yes

Decisions no print('More than one’)

x = 42
if x > 1 : yes
print('More than one') x < 100
if x < 100 :
no
print('Less than 100') print('Less than 100')
print('All done')

print('All Done')
Two-way Decisions
x=4

• Sometimes we want to
do one thing if a logical no yes
x>2
expression is true and
something else if the
expression is false print('Not bigger') print('Bigger')

• It is like a fork in the


road - we must choose
one or the other path but print('All Done')
not both
Two-way Decisions
x=4
with else:
no yes
x = 4 x>2

if x > 2 :
print('Bigger') print('Not bigger') print('Bigger')
else :
print('Smaller')

print('All done')
print('All Done')
Visualize Blocks x=4

no yes
x = 4 x>2

if x > 2 :
print('Bigger') print('Not bigger') print('Bigger')
else :
print('Smaller')

print('All done')
print('All Done')
More Conditional Structures…
Multi-way
yes
x<2 print('small')
no
if x < 2 :
yes
print('small')
elif x < 10 :
x < 10 print('Medium')
print('Medium') no
else :
print('LARGE') print('LARGE')
print('All done')

print('All Done')
x=0
Multi-way
yes
x<2 print('small')
x = 0
no
if x < 2 :
yes
print('small')
elif x < 10 :
x < 10 print('Medium')
print('Medium') no
else :
print('LARGE') print('LARGE')
print('All done')

print('All Done')
x=5
Multi-way
yes
x<2 print('small')
x = 5
no
if x < 2 :
yes
print('small')
elif x < 10 :
x < 10 print('Medium')
print('Medium') no
else :
print('LARGE') print('LARGE')
print('All done')

print('All Done')
x = 20
Multi-way
yes
x<2 print('small')
x = 20
no
if x < 2 :
yes
print('small')
elif x < 10 :
x < 10 print('Medium')
print('Medium') no
else :
print('LARGE') print('LARGE')
print('All done')

print('All Done')
Multi-way if x < 2 :
print('Small')
elif x < 10 :
# No Else print('Medium')
x = 5 elif x < 20 :
if x < 2 : print('Big')
print('Small') elif x < 40 :
elif x < 10 : print('Large')
print('Medium') elif x < 100:
print('Huge')
print('All done') else :
print('Ginormous')
Multi-way Puzzles
Which will never print
regardless of the value for x?
if x < 2 :
print('Below 2')
if x < 2 : elif x < 20 :
print('Below 2') print('Below 20')
elif x >= 2 : elif x < 10 :
print('Two or more') print('Below 10')
else : else :
print('Something else') print('Something else')
Python Logical Operators
Logical operators are used to combine conditional statements:
Python Logical Operators
The try / except Structure

• You surround a dangerous section of code with try and except

• If the code in the try works - the except is skipped

• If the code in the try fails - it jumps to the except section


astr = 'Hello Bob' When the first conversion fails - it
try: just drops into the except: clause
istr = int(astr) and the program continues.
except:
istr = -1
$ python [Link]
print('First', istr) First -1
Second 123
astr = '123'
try:
istr = int(astr)
except:
istr = -1 When the second conversion
succeeds - it just skips the except:
print('Second', istr) clause and the program continues.
astr = 'Bob'
try / except
print('Hello')
astr = 'Bob'
try:
print('Hello') istr = int(astr)
istr = int(astr)
print('There')
except: print('There')
istr = -1
istr = -1
print('Done', istr)

print('Done', istr) Safety net


try / except / Finally
Summary
• Comparison operators • Nested Decisions
== <= >= > < !=
• Multi-way decisions using elif
• Indentation
• try / except to compensate for
• One-way Decisions errors
• Two-way decisions:
if: and else:
Exercise

Rewrite your pay computation to give the


employee 1.5 times the hourly rate for hours
worked above 40 hours.

Enter Hours: 45
Enter Rate: 10

Pay: 475.0
475 = 40 * 10 + 5 * 15
Exercise

Rewrite your pay program using try and except so


that your program handles non-numeric input
gracefully.

Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input

Enter Hours: forty


Error, please enter numeric input

Common questions

Powered by AI

Python's multi-way decision structure using 'elif' allows for more than two branching paths based on multiple conditions, compared to the binary nature of traditional if-else structures. 'Elif' stands for 'else if', letting the program evaluate multiple conditional statements sequentially. This approach reduces code complexity and avoids deeply nested if-else constructs, improving readability and maintainability by clearly defining alternative pathways in a single level of indentation .

Indentation in Python is crucial as it defines the block of statements controlled by structures like if, for, and while. Proper indentation signifies that blocks of code are part of a particular control structure, which is mandatory since Python lacks explicit block delimiters. Misalignment or inconsistent use of tabs and spaces can result in syntax errors or logical missteps in program execution, making proper indentation a significant aspect of Python coding style .

Logical operators in Python, such as 'and', 'or', and 'not', are used to combine multiple conditions in decision-making constructs. These operators enable more complex conditions as they allow for the evaluation of multiple expressions simultaneously. For instance, a program might check if a number is between two values with the expression 'if x > 5 and x < 10', executing code only if both conditions are true .

Common comparison operators in Python include '==', '<', '>', '<=', '>=', and '!='. These operators evaluate relationships between variables or values, returning Boolean results which are used in conditional statements to control program flow. For example, '==' checks if two values are equal, '<' checks if one value is less than another, and '!=' checks if values are not equal .

A simple Python program for pay computation with input validation using try/except might look like this: ```python try: hours = float(input('Enter Hours: ')) rate = float(input('Enter Rate: ')) if hours > 40: pay = 40 * rate + (hours - 40) * rate * 1.5 else: pay = hours * rate print(f'Pay: {pay}') except ValueError: print('Error, please enter numeric input') ``` In this code, the try block attempts to read and convert the user input to floats. If the conversion fails (e.g., the user enters a non-numeric value), the except block catches the ValueError and prints an error message, preventing the program from crashing and allowing the user to try again .

Using try-except blocks for handling integer conversions and custom errors enhances a program's robustness by allowing the script to detect and manage errors dynamically. Such blocks can catch exceptions arising from invalid user input, such as trying to convert non-numeric strings to integers, and respond with meaningful messages or corrective actions, rather than terminating unexpectedly. This ensures ongoing program stability, improves user experience, and prevents unhandled exceptions from cascading into broader failures .

In Python conditionals, the 'else' clause provides a block of code that executes if the preceding 'if' or 'elif' conditions evaluate to False. This ensures that some code runs if none of the conditional statements are met, similar to a catch-all. For example, in a user input validation scenario, if a value is not within a given range of acceptable inputs, the 'else' clause may trigger an error message to the user, facilitating error handling .

If a comparison condition fails within a try-except block, Python will immediately jump to the except block, bypassing any code remaining in the try block. This allows the program to handle the error gracefully by executing predefined responses or fallback actions in the except block, without crashing or requiring user intervention .

The try/except structure in Python is used to manage code that may cause errors during execution. When an error occurs within the 'try' block, Python will move to execute the 'except' block, allowing the program to continue running without crashing. For example, in converting a string to an integer where the input may not always be numeric, the code inside the 'try' can attempt the conversion, and if it fails, the 'except' block can assign a default value or print an error message .

In Python, the level of indentation denotes the scope of code blocks, such as those following if statements or loops. If the indentation is inconsistent, it may cause 'indentation errors,' which can lead to run-time errors or unexpected behaviors since the Python interpreter will not correctly associate statements with their controlling structures . Mixing tabs and spaces can visually appear correct but actually break the program flow because they are interpreted differently by the interpreter, potentially creating logical or syntax errors .

You might also like