If-else statement and loop
5/2/2018
1
Decision Structures and Boolean Logic
Selected slides from Gaddis, “Starting out with Python”, 4th edition.
Topics
• The if Statement
• The if-else Statement
• Comparing Strings
• Nested Decision Structures and the if-elif-else Statement
• Logical Operators
• Boolean Variables
5/2/2018
2
The if Statement
• Control structure: logical design that controls order in which set of statements execute
• Sequence structure: set of statements that execute in the order they appear
• Decision structure: specific action(s) performed only if a condition exists • Also known as selection structure
The if Statement (cont’d.)
• In flowchart, diamond represents true/false condition that must be tested
• Actions can be conditionally executed • Performed only when a condition is true
• Single alternative decision structure: provides only one alternative path of execution • If condition is not true, exit the structure
5/2/2018
3
The if Statement (cont’d.)
The if Statement (cont’d.)
• Python syntax: if condition:
Statement
Statement
• First line known as the if clause • Includes the keyword if followed by condition
• The condition can be true or false
• When the if statement executes, the condition is tested, and if it is true the block statements are executed. otherwise, block statements are skipped
5/2/2018
4
Boolean Expressions and Relational Operators
• Boolean expression: expression tested by if statement to determine if it is true or false • Example: a > b
• true if a is greater than b; false otherwise
• Relational operator: determines whether a specific relationship exists between two values • Example: greater than (>)
3-8
Relational Operators
• In most cases, the boolean expression, used by the if statement, uses relational operators.
Relational Operator Meaning
> is greater than
< is less than
>= is greater than or equal to
<= is less than or equal to
== is equal to
!= is not equal to
5/2/2018
5
Boolean Expressions and Relational Operators (cont’d.) • >= and <= operators test more than one relationship
• It is enough for one of the relationships to exist for the expression to be true
• == operator determines whether the two operands are equal to one another • Do not confuse with assignment operator (=)
• != operator determines whether the two operands are not equal
Boolean Expressions and Relational Operators (cont’d.)
5/2/2018
6
Boolean Expressions and Relational Operators (cont’d.) • Using a Boolean expression with the > relational operator
Boolean Expressions and Relational Operators (cont’d.) • Any relational operator can be used in a decision block
• Example: if balance == 0
• Example: if payment != balance
• It is possible to have a block inside another block • Example: if statement inside a function
• Statements in inner block must be indented with respect to the outer block
5/2/2018
7
The if-else Statement
• Dual alternative decision structure: two possible paths of execution – One is taken if the condition is true, and the other if the condition is false
• Syntax: if condition: statements
else:
other statements
• if clause and else clause must be aligned
• Statements must be consistently indented
The if-else Statement (cont’d.)
5/2/2018
8
The if-else Statement (cont’d.)
Comparing Strings
• Strings can be compared using the == and != operators
• String comparisons are case sensitive
• Strings can be compared using >, <, >=, and <= • Compared character by character based on the ASCII values for each
character
• If shorter word is substring of longer word, longer word is greater than shorter word
5/2/2018
9
Comparing Strings (cont’d.)
Nested Decision Structures and the if-elif- else Statement
• A decision structure can be nested inside another decision structure • Commonly needed in programs
• Example: • Determine if someone qualifies for a loan, they must meet two conditions:
• Must earn at least $30,000/year
• Must have been employed for at least two years
• Check first condition, and if it is true, check second condition
5/2/2018
10
Nested Decision Structures and the if-elif-else Statement (cont’d.)
• Important to use proper indentation in a nested decision structure • Important for Python interpreter
• Makes code more readable for programmer
• Rules for writing nested if statements: • else clause should align with matching if clause
• Statements in each block must be consistently indented
5/2/2018
11
The if-elif-else Statement
• if-elif-else statement: special version of a decision structure • Makes logic of nested decision structures simpler to write
• Can include multiple elif statements
• Syntax:
if condition_1:
statement(s)
elif condition_2:
statement(s)
elif condition_3:
statement(s)
else
statement(s)
Insert as many elif clauses
as necessary.
The if-elif-else Statement (cont’d.) • Alignment used with if-elif-else statement:
• if, elif, and else clauses are all aligned
• Conditionally executed blocks are consistently indented
• if-elif-else statement is never required, but logic easier to follow • Can be accomplished by nested if-else
• Code can become complex, and indentation can cause problematic long lines
5/2/2018
12
Logical Operators
• Logical operators: operators that can be used to create complex Boolean expressions • and operator and or operator: binary operators, connect two Boolean
expressions into a compound Boolean expression
• not operator: unary operator, reverses the truth of its Boolean operand
5/2/2018
13
The and Operator
• Takes two Boolean expressions as operands • Creates compound Boolean expression that is true only when both sub
expressions are true
• Can be used to simplify nested decision structures
• Truth table for
the and operator Value of the Expression
Expression
falsefalse and false
falsefalse and true
falsetrue and false
truetrue and true
The or Operator
• Takes two Boolean expressions as operands • Creates compound Boolean expression that is true when either of the sub
expressions is true
• Can be used to simplify nested decision structures
• Truth table for
the or operator Value of the Expression
Expression
falsefalse and false
truefalse and true
truetrue and false
truetrue and true
5/2/2018
14
Short-Circuit Evaluation
• Short circuit evaluation: deciding the value of a compound Boolean expression after evaluating only one sub expression • Performed by the or and and operators
• For or operator: If left operand is true, compound expression is true. Otherwise, evaluate right operand
• For and operator: If left operand is false, compound expression is false. Otherwise, evaluate right operand
The not Operator
• Takes one Boolean expressions as operand and reverses its logical value • Sometimes it may be necessary to place parentheses around an expression to
clarify to what you are applying the not operator
• Truth table for the not operator
Value of the ExpressionExpression
falsetrue
truefalse
5/2/2018
15
Checking Numeric Ranges with Logical Operators • To determine whether a numeric value is within a specific range of
values, use and Example: x >= 10 and x <= 20
• To determine whether a numeric value is outside of a specific range of values, use or
Example: x < 10 or x > 20
Testing, Searching, and Manipulating Strings
5/2/2018
16
String Manipulation Functions
•.replace()
line = line.replace(old,new) #changes all instance of old to new
Example: line = "My CAR is cool, my CAR is awesome!" line = line.replace(“CAR”,”BUS”) print (line)
32
Application- Biological sequences
• Nucleic acid sequences are represented as strings of A,T,C,G,U (for RNA only) and N (unknown)
• Protein sequences are represented by strings from the standard IUB/IUPAC amino acid codes
5/2/2018
17
33
DNA Transcription and Translation
• DNA: TCGGGAGCT
• RNA: UCGGGAGCU
• Protien: SGA
Application – Transcription # Purpose: Transcribes DNA into RNA
# Print the DNA onto the screen
DNA = "ACGGGCGCGATTTTATTAC"
print ("Here is the starting DNA:")
print (DNA)
# Transcribe the DNA to RNA by substituting all T's with U's.
RNA = DNA.replace("T","U")
# Print the RNA onto the screen
print ("Here is the result of transcribing the DNA to RNA:")
print (RNA)
34