Chapter 9 IF Statement

14
Chapter 9 IF Statement Bernard Chen

description

Chapter 9 IF Statement. Bernard Chen. If Statement. The main statement used for selecting from alternative actions based on test results It’s the primary selection tool in Python and represents the Logic process. Some Logic Expression. Equal: “==” NOT Equal: “!=” Greater: “>”, “>=” - PowerPoint PPT Presentation

Transcript of Chapter 9 IF Statement

Page 1: Chapter 9  IF Statement

Chapter 9 IF Statement

Bernard Chen

Page 2: Chapter 9  IF Statement

If Statement

The main statement used for selecting from alternative actions based on test results

It’s the primary selection tool in Python and represents the Logic process

Page 3: Chapter 9  IF Statement

Some Logic Expression

Equal: “==”

NOT Equal: “!=”

Greater: “>”, “>=”

Less than: “<”, “<=”

Page 4: Chapter 9  IF Statement

Outline

Simple If statement If... else statement If… else if … else statement

Page 5: Chapter 9  IF Statement

Simple If statement

It takes the form of an if test

if <test>: <statement>

Page 6: Chapter 9  IF Statement

Simple If statement if 4>3: print “it is true that 4>3”

if 1: print “true”

a=10 if a==10:

print “a=10”

Page 7: Chapter 9  IF Statement

If... else statement

It takes the form of an if test, and ends with an optional else block

if <test>: <statement1> else: <statement2>

Page 8: Chapter 9  IF Statement

If... else statement if 3>4: print “3 is larger than 4” else: print “3 is NOT larger than 4”

if 0: print “true” else: print “false”

Page 9: Chapter 9  IF Statement

If... else statement a=10 if a==10:

print “a=10” else: print “a is not equal to 10”

a=10 if a!=10:

print “a=10” else: print “a is not equal to 10”

(also try >, < )

Page 10: Chapter 9  IF Statement

If… else if … else statement It takes the form of an if test, followed

by one or more optional elif tests, and ends with an optional else block

if <test1>: <statement1>elif <test2>:

<statement2>else: <statement3>

Page 11: Chapter 9  IF Statement

If… else if … else statement

a=10 if a>10:

print “a > 10” elif a==10:

print “a = 10” else: print “a < 10”

Page 12: Chapter 9  IF Statement

If… else if … else statement examplenumber = 23guess = int(raw_input('Enter an integer : '))

if guess == number:print 'Congratulations, you guessed it.' # New block starts hereprint "(but you do not win any prizes!)" # New block ends here

elif guess < number:print 'No, it is a little higher than that' # Another block# You can do whatever you want in a block ...

else:print 'No, it is a little lower than that'# you must have guess > number to reach here

Page 13: Chapter 9  IF Statement

Some More Logic Expression

and >>> 5>4 and 8>7True>>> 5>4 and 8>9False

Page 14: Chapter 9  IF Statement

Some More Logic Expression

or >>> 5>4 or 8>7True>>> 5>4 or 8>9True