Transcript Part 3

Python 3
SIGCS 1
Intro to Python
March 7, 2012
Presented by
Pamela A Moore & Zenia C Bahorski
1
Boolean operators
• Statements using Boolean operators have a
value of either true or false
• Equivalency operator "=="
- returns either True or False
• Ex: 4 == 5 would be false
• Ex: (assume x has been set to 73)
• x == 70 would be False
• x == 73 would be True
2
Boolean operators
•
•
•
•
•
•
•
•
return either True or False
and, or, not, in, not in
Ex: 4 == 5 and 1==1 would be False
Ex: 4 == 5 or 1==1 would be True
Ex: not 1==1 would be False
Ex: 6 in range(12) would be True
Ex: 6 in range(4) would be False
What would 6 in range(6) be?
3
Multiple Boolean operators
• Ex: print a or b or c
• First true expression is printed, others
ignored
4
Other division operators
• // operator – returns the integer portion of
division
• Ex: 3 // 2 would be 1
• Ex: 6 // 3 would be 2
• Ex: 3 // 4 would be 0
5
Other division operators
• % operator – returns the integer remainder of
division – also called the "mod" operator
• Ex: 3 % 2 would be 1
• Ex: 6 % 3 would be 0
• Ex: 3 % 4 would be 3
6
Other mathematical
operators
• += operator – shorthand for adding to a
variable
• Ex: x += 3 would be equivalent to x = x+3
7
Other mathematical
operators
• -= operator – shorthand for subtracting from a
variable
• Ex: x -= 3 would be equivalent to x = x-3
8
Conditionals
• If statements
• If - else statements
• If - elif - else statements
9
If statement
• Used to make a choice
• Ex: if number == 3:
print "The number is 3!"
print "This is here just to have more in the block"
• This will print only if the value of number
is equivalent to 3
10
If - else statement
• Conditional for an either/or situation
• Only one part will be executed
• Ex: if num == 3:
print "num is 3"
else:
print "num is not 3"
11
If - elif - else statement
• Conditional for multiple choice situation
• Only one part will be executed.
• Ex: if num == 3:
print "num is 3"
elif num == 4:
print "num is 4"
else:
print "num is not 3 or 4"
12
When you want to do
nothing
• Occasionally there is a reason to put in
code that does nothing.
• The pass statement just sends the
interpreter on to the next statement.
• Ex: if code == "Done":
print "all done"
else:
pass
Do: Example 3
13