View
224
Download
4
Embed Size (px)
Citation preview
Conditional StatementsConditional Statements
Introduction to Computing Introduction to Computing Science and Programming IScience and Programming I
Conditional StatementsConditional Statements
So far we have only talked about So far we have only talked about writing statements that are executed writing statements that are executed one after another from top to bottomone after another from top to bottom
This simply isn’t sufficient to write This simply isn’t sufficient to write very many useful programsvery many useful programs
Simple Guessing GameSimple Guessing Game
Here is an algorithm for a very simple Here is an algorithm for a very simple guessing game.guessing game.write “Think of a number between 1 and 10.”set guess to 6.write “Is your number equal to guess?”read answerif answer is “yes”, then
write “I got it right!”if answer isn’t “yes”, then
write “Nuts.”write “That’s the end of the game.”
Simple Guessing GameSimple Guessing Game
Looking at this algorithm we see that Looking at this algorithm we see that there are statements that will be run there are statements that will be run under certain conditions, but not under certain conditions, but not others.others.
if answer is “yes”, thenwrite “I got it right!”
if answer isn’t “yes”, thenwrite “Nuts.”
Simple Guessing GameSimple Guessing Game
Depending on the value of answer Depending on the value of answer we will do one of two different things.we will do one of two different things.
If you want to write code like this If you want to write code like this that will execute if a certain that will execute if a certain condition is true, you use an if condition is true, you use an if structurestructure
If StructureIf Structure
if if conditioncondition::statement1statement1statement2statement2
statement3statement3
If the condition is satisfied when execution If the condition is satisfied when execution reaches the if statement, then all reaches the if statement, then all statements that are indented after it will statements that are indented after it will be executed. If the condition is not be executed. If the condition is not satisfied then they will be skipped and satisfied then they will be skipped and execution will continue after the indented execution will continue after the indented statementsstatements
Blocks of CodeBlocks of Code
Python uses indentation to indicate Python uses indentation to indicate blocks of code.blocks of code.
For an if statement we indent every For an if statement we indent every statement in the block of code that will statement in the block of code that will be executed based on the result of the be executed based on the result of the ififif x==1:if x==1:
print “first line of code block”print “first line of code block”
print “last line of code block”print “last line of code block”
print “first line outside of code block”print “first line outside of code block”
Blocks of CodeBlocks of Code
Blocks of Code can be within other Blocks of Code can be within other blocks of codeblocks of code
11 if x > 5:if x > 5:
22 print “x is greater than 5”print “x is greater than 5”
33 if x > 10:if x > 10:
44 print “x is also greater than 10”print “x is also greater than 10”
Lines 2, 3, and 4 are the block of Lines 2, 3, and 4 are the block of code for the first if statement. Line 4 code for the first if statement. Line 4 is the block of code for the second if is the block of code for the second if statementstatement
Guessing GameGuessing Game Here is how the guessing game is translated into Here is how the guessing game is translated into
PythonPython
print "Think of a number between 1 and 10.“print "Think of a number between 1 and 10.“guess = 6 guess = 6 answer = raw_input("Is your number equal to “ + \ answer = raw_input("Is your number equal to “ + \
str(guess) + "? ") str(guess) + "? ") if answer == "yes": if answer == "yes":
print "I got it right!" print "I got it right!" if answer != "yes": if answer != "yes":
print "Nuts." print "Nuts." print "That's the end of the game." print "That's the end of the game."
The bool Data TypeThe bool Data Type
Before this point all of the Before this point all of the expressions we have used evaluate expressions we have used evaluate to either a string, integer, or float.to either a string, integer, or float.
For the if statement we have a For the if statement we have a condition that Python will evaluate to condition that Python will evaluate to be either True or False. These be either True or False. These conditions are boolean expressions conditions are boolean expressions for which we have the bool data typefor which we have the bool data type
The bool Data TypeThe bool Data Type
For the guessing game we have two For the guessing game we have two conditional statements that contain conditional statements that contain simple boolean expressionssimple boolean expressions
answer == “yes”answer == “yes” Evaluates to True if answer is equal to Evaluates to True if answer is equal to
“yes”“yes” answer != “yes”answer != “yes”
Evaluates to True if answer is not equal Evaluates to True if answer is not equal to “yes”to “yes”
Boolean OperatorsBoolean Operators
Comparison OperatorsComparison Operators ==, is equal to==, is equal to
This is different from =This is different from = x=5, assigns x the value 5x=5, assigns x the value 5 x==5, a boolean expression that evaluates to x==5, a boolean expression that evaluates to
True if x is equal to 5, False if is notTrue if x is equal to 5, False if is not
!=, is not equal to!=, is not equal to Returns the opposite of ==Returns the opposite of ==
x!=5 is true if x does not equal 5x!=5 is true if x does not equal 5
<, >, <=, >= all act as you’d expect<, >, <=, >= all act as you’d expect
Boolean OperatorsBoolean Operators
Logical OperatorsLogical Operators and, &and, &
A and B is true if both A and B are TrueA and B is true if both A and B are Truex=5x=5(x > 1 and x < 4) is False(x > 1 and x < 4) is False
or, |or, | A or B is true if either A or B is TrueA or B is true if either A or B is True
x=5x=5(x > 1 or x < 4) is True(x > 1 or x < 4) is True
not, !not, ! not A is true if A is Falsenot A is true if A is False
x=5x=5not x < 4 is Truenot x < 4 is True
Boolean VariablesBoolean Variables
Since bool is a data type, you can Since bool is a data type, you can store a bool value into a variable as store a bool value into a variable as with any other data typewith any other data type
x=int(raw_input(“Enter an integer between 0 and 10: x=int(raw_input(“Enter an integer between 0 and 10: ”))”))
xIsInCorrectRange = (x >= 0 and x <= 10)xIsInCorrectRange = (x >= 0 and x <= 10)if not xIsInCorrectRange:if not xIsInCorrectRange: print “You didn’t enter an integer between 0 and 10”print “You didn’t enter an integer between 0 and 10” print “I’m giving you the number 5”print “I’m giving you the number 5” x=5x=5print “Your number is “ + str(x) + “.”print “Your number is “ + str(x) + “.”
else Clauseelse Clause
if if conditioncondition::code block1code block1
else:else:code block2code block2
If the condition is satisfied when execution If the condition is satisfied when execution reaches the if statement, then code block1 reaches the if statement, then code block1 will be executed. Otherwise, code block2 will be executed. Otherwise, code block2 will be executedwill be executed
else Clauseelse Clause In our guessing game example we can simplify the In our guessing game example we can simplify the
code using an else clause instead of a second if code using an else clause instead of a second if statementstatement We have this, but we know that if the first condition is false We have this, but we know that if the first condition is false
the second is truethe second is trueif answer == “yes”:if answer == “yes”:
print “I got it right.”print “I got it right.”
if answer != “yes”:if answer != “yes”:print “Nuts.”print “Nuts.”
We can use an else clause. If the condition in the if We can use an else clause. If the condition in the if statement is false execution will move to the associated statement is false execution will move to the associated else clause.else clause.
if answer == “yes”:if answer == “yes”:print “I got it right.”print “I got it right.”
else:else:print “Nuts.”print “Nuts.”
elif Clauseselif Clauses
elif is how Python shortens else-ifelif is how Python shortens else-if elif clauses can be used if there are elif clauses can be used if there are
multiple related conditions you want multiple related conditions you want to check for and execute different to check for and execute different code depending on which one is truecode depending on which one is true
elif Clauseselif Clauses
if if condition1condition1::code block1code block1
elif condition2:elif condition2:code block2code block2
..
..else:else:
code blockcode block
If condition1 is true, code block1 will be executed and the If condition1 is true, code block1 will be executed and the other clauses will be skipped, otherwise if condition2 is other clauses will be skipped, otherwise if condition2 is true, code block2 will be executed, and so on. If none of true, code block2 will be executed, and so on. If none of the conditions are true and there is an else clause, the code the conditions are true and there is an else clause, the code block for that clause will be executed. You can use as block for that clause will be executed. You can use as many elif clauses as needed.many elif clauses as needed.
elif Clauseselif Clauses
One more extension of the guessing One more extension of the guessing game using an elif clause.game using an elif clause.
if answer == "yes": print "I got it right!"elif answer == "no": print "Nuts."else: print "You must answer ’yes’ or ’no’.“
elif Clauseselif Clauses Remember that only the first elif clause whose condition is Remember that only the first elif clause whose condition is
satisfied will have its block of code executed.satisfied will have its block of code executed.
weight = int(raw_input("How many grams does the object weight = int(raw_input("How many grams does the object weight? "))weight? "))
if weight >1000:if weight >1000: print "It weighs " + str(weight/1000.0) + " kilograms."print "It weighs " + str(weight/1000.0) + " kilograms."elif weight > 100:elif weight > 100: print "It weighs " + str(weight/100.0) + " hectograms."print "It weighs " + str(weight/100.0) + " hectograms."elif weight > 10:elif weight > 10: print "It weighs " + str(weight/10.0) + " dekagrams."print "It weighs " + str(weight/10.0) + " dekagrams."elif weight >= 0:elif weight >= 0: print "It weighs " + str(weight) + " grams."print "It weighs " + str(weight) + " grams."else:else: print "You entered an invalid number."print "You entered an invalid number."
elif Clauseselif Clauses Easy way to set up a simple menu.Easy way to set up a simple menu.
print “1. Create a new file”print “1. Create a new file”print “2. Open a file”print “2. Open a file”print ”3. Exit”print ”3. Exit”x = int(raw_input(“Select an option: “))x = int(raw_input(“Select an option: “))if x==1:if x==1:
..
..elif x==2:elif x==2:
..
..elif x==3:elif x==3:
..
..else:else:
print “You didn’t enter a valid option.”print “You didn’t enter a valid option.”