Date post: | 22-Feb-2017 |
Category: |
Career |
Upload: | primeteacher32 |
View: | 185 times |
Download: | 0 times |
DECISION STRUCTURES
Review Conditionals A conditional is what we refer to as a decision
structure. Where a decision is made is based upon a set of rules. We mainly will be working with the if…then. Ie. If an event occurs then a certain outcome
will happen.
Ex. If it rains, then I will wear a rain coat.
Review Conditionals Conditional arguments are Boolean expressions.
Question: Meaning??? We use relational operators to form Boolean
expressions. Operator Meaning
== equal to < less than <= less than or equals to > greater than >= greater than or equal to != not equal to
Common Mistake: Confusing = with ==
Code
Code:Creating a decision structure: if (expression):statement
To execute more than one statement in a block they must be indented equally:
if (score > 90): grade = 'A' print(“Good Job!\n”)
Good Programming: Commenting conditional blocks Common Mistakes: Forgetting equal indent, forgetting :, and
forgetting space after if
SpaceIndent
if Statement Example
Reviewing If…Else We can nest conditional statements to have
several decision structures within one statement.
This allows an application to check multiple situations for 1 desired outcome
Allows us to simplify code by not having as many separate if statements. Ie. If an event occurs then a certain outcome
will happen, else do something different Ex.
If it rains, then I will wear a rain coat else I don’t need a jacket.
Flipping a coin if not heads it must be tails(100% outcomes)
CodeCreating a nested conditional:
if (condition): statement else: statement
Good Programming: We usually line up else with the preceding if to make it easier to find errors.
Question: Be careful testing real numbers for equality, why?
if/else Example
If…ElIf We can nest conditional statements to have
several decision structures within one statement in order to test various situations for a desired result.
Ie. If an event occurs then a certain outcome will happen Or else if this happens do this or else do something else
We can nest as many ElseIf’s together but each set of conditionals can have only one Else statement otherwise it will create a logical error
Ex. If it rains, then I will wear a rain coat else if it snows
then I will wear gloves or else I won’t need a jacket. Rolling a die 1,2,3,4,5,6 if lands on 1 don’t need to
check other sides b/c 100% of outcomes
CodeCreating a nested conditional:
if (condition):Statement
elif (condition):Statement
elif (condition):StatementStatement
else: Statement
Common Errors: Not Lining up Else with its
preceding If. Question: Why is a trailing else good programming?
Nested if/else if Example
Question: What zodiac sign is it for the current year?
Nested if Statements