Learning python - part 2 - chapter 4

Post on 19-May-2015

153 views 0 download

Tags:

description

Learning python series based on "Beginning Python Using Python 2.6 and P - James Payne" book presented by Koosha Zarei.

Transcript of Learning python - part 2 - chapter 4

Learning PythonPart 2 | Winter 2014 | Koosha Zarei | QIAU

Part 2Chapter 4 – Making Decisions

3February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

Comparing Values — Are They the Same?Doing the Opposite — Not EqualComparing Values — Which One Is More?Reversing True and FalseLooking for the Results of More Than One ComparisonHow to Get Decisions MadeRepetition

Content

4February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

Comparing Values — Are They the Same?

True and False are the results of comparing values, asking questions, and performing other actions.However, anything that can be given a value and a name can be compared with the set of comparison operations that return True and False.

>>> 1 == 1True>>> 1 == 2False

>>> 1.23 == 1False>>> 1.0 == 1True

5February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

Comparing Values — Are They the Same?

>>> a = “Mackintosh apples”>>> b = “Black Berries”>>> c = “Golden Delicious apples”>>> a == bFalse>>> b == cFalse>>> a[-len(“apples”):-1] == c[-len(“apples”):-1]True

6February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

Doing the Opposite — Not Equal

There is an opposite operation to the equality comparison. If you use the exclamation and equals together, you are asking Python for a comparison between any two values that are not equal to result in a True value.

>>> 3 == 3True>>> 3 != 3False>>> 5 != 4True

7February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

Comparing Values — Which One Is More?

Sometimes you will want to know whether a quantity of something is greater than that of another, or whether a value is less than some other value. Python has greater than and less than operations that can be invoked with the > and < characters, respectively.

>>> 5 < 3False>>> 10 > 2True

8February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

Comparing Values — Which One Is More?

>>> “Zebra” > “aardvark”False>>> “Zebra” > “Zebrb”False>>> “Zebra” < “Zebrb”True

>>> “a” > “b”False>>> “A” > “b”False>>> “A” > “a”False>>> “b” > “A”True>>> “Z” > “a”False

9February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

Comparing Values — Which One Is More?

>>> “Pumpkin” == “pumpkin”False>>> “Pumpkin”.lower() == “pumpkin”.lower()True>>> “Pumpkin”.lower()‘pumpkin’>>> “Pumpkin”.upper() == “pumpkin”.upper()True>>> “pumpkin”.upper()‘PUMPKIN’

10February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

Comparing Values — Which One Is More?

>>> 1 > 1False>>> 1 >= 2False>>> 10 < 10False>>> 10 <= 10True

11February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

Reversing True and FalseWhen you are creating situations and comparing their outcomes, sometimes you want to know whether something is true, and sometimes you want to know whether something is not true. Sensibly enough, Python has an operation to create the opposite situation — the word not provides the opposite of the truth value that follows it.

>>> not TrueFalse>>> not 5False>>> not 0True>>> Not TrueSyntaxError: invalid syntax (<pyshell#30>, line 1)

12February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

Looking for the Results of More Than One Comparison

You can also combine the results of more than one operation, which enables your programs to make more complex decisions by evaluating the truth values of more than one operation.

One kind of combination is the and operation, which says “if the operation, value, or object on my left evaluates to being True, move to my right and evaluate that. If it doesn’t evaluate to True, just stop and say False — don’t do any more.”

13February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

Looking for the Results of More Than One Comparison

>>> True and TrueTrue>>> False and TrueFalse>>> True and FalseFalse>>> False and FalseFalse

14February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

Looking for the Results of More Than One Comparison

The other kind of combining operation is the or operator. Using the or tells Python to evaluate the expression on the left, and if it is False, Python will evaluate the expression on the right. If it is True, Python will stop evaluation of any more expressions.

>>> True or TrueTrue>>> True or FalseTrue>>> False or TrueTrue>>> False or FalseFalse

15February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

How to Get Decisions MadePython has a very simple way of letting you make decisions. The reserved word for decision making is if, and it is followed by a test for the truth of a condition, and the test is ended with a colon.

>>> if 1 > 2:… print(“No it is not!”)...>>> if 2 > 1:… print(“Yes it is!”)...Yes, it is!

16February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

How to Get Decisions MadeIf statement

In simple terms, the Python if statement selects actions to perform.The if statement may contain other statements, including other ifs.

if <test1>: #if test<statements1> # Associated block

elif <test2>: # Optional elifs<statements2>

Else: # Optional else<statements3>

x = 'killer rabbit'if x == 'roger':

print("how's jessica?")elif x == 'bugs':

print("what's up doc?")else:

print('Run away! Run away!')

Run away! Run away!

17February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

How to Get Decisions MadeIf you’ve used languages like C or Pascal, you might be interested to know that there is no switch or case statement in Python that selects an action based on a variable’s value.

Instead, multiway branching is coded either as a series of if/elif tests, or by indexing dictionaries or searching lists.

18February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

How to Get Decisions MadeThis dictionary is a multiway branch—indexing on the key choice branches to one of a set of values, much like a switch in C.

>>> choice = 'ham'>>> print({'spam': 1.25, # A dictionary-based 'switch'… 'ham': 1.99, # Use has_key or get for default… 'eggs': 0.99,… 'bacon': 1.10}[choice])

1.99

19February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

How to Get Decisions MadeAn almost equivalent but more verbose Python if statement.

Notice the else clause on the if here to handle the default case when no key matches.

>>> if choice == 'spam':… print(1.25)... elif choice == 'ham':… print(1.99)... elif choice == 'eggs':… print(0.99)... elif choice == 'bacon':… print(1.10)... else:… print('Bad choice')...1.99

20February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

How to Get Decisions Made>>> branch = {'spam': 1.25,… 'ham': 1.99,… 'eggs': 0.99}>>> print(branch.get('spam', 'Bad choice'))1.25>>> print(branch.get('bacon', 'Bad choice'))Bad choice

>>>choice = 'bacon'>>>if choice in branch:… print(branch[choice])… else:… print('Bad choice')

Bad choice

21February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

How to Get Decisions MadePython Syntax Rules

Statements execute one after another, until you say otherwise.Block and statement boundaries are detected automatically.Compound statements = header + “:” + indented statements.Blank lines, spaces, and comments are usually ignored.Docstrings are ignored but are saved and displayed by tools.

22February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

RepetitionThere may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially.

Loop Type Descriptionwhile loop Repeats a statement or group of statements while a

given condition is true. It tests the condition beforeexecuting the loop body.

for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

nested loops You can use one or more loop inside any another while, for or do..while loop.

23February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

RepetitionWhile loop

Python’s while statement is the most general iteration construct in the language.It repeatedly executes a block of statements as long as a test at the top keeps evaluating to a true value.

while <test>: # Loop test<statements1> # Loop body

else: # Optional else<statements2> # Run if didn't exit loop with break

24February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

RepetitionWhile loop

>>> x = 'spam'>>> while x: # While x is not empty… print(x, end=' ')… x = x[1:] # Strip first character off x…spam pam am m

>>> a=0; b=10>>> while a < b: # One way to code counter loops… print(a, end=' ')… a += 1 # Or, a = a + 1...0 1 2 3 4 5 6 7 8 9

25February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

Repetitionfor loop

The for loop in Python has the ability to iterate over the items of any sequence, such as a list or a string.it can step through the items in any ordered sequence object.The for statement works on strings, lists, tuples, other built-in iterables.

for <target> in <object>: # Assign object items to target<statements> # Repeated loop body: use target

else:<statements> # If we didn't hit a 'break'

26February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

Repetitionfor loop

for <target> in <object>: # Assign object items to target<statements>if <test>: break # Exit loop now, skip elseif <test>: continue # Go to top of loop now

else:<statements> # If we didn't hit a 'break'

>>> for x in ["spam", "eggs", "ham"]:… print(x, end=' ')...spam eggs ham

27February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

Repetitionfor loop

>>> S = "lumberjack">>> for x in S: # Iterate over a string... print(x, end=' ')

l u m b e r j a c k

>>> T = [(1, 2), (3, 4), (5, 6)]>>> for (a, b) in T:… print(a, b)...1 23 45 6

>>> D = {'a': 1, 'b': 2, 'c': 3}>>> for key in D:… print(key, '=>', D[key])...a => 1c => 3b => 2

28February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

Repetitionfor loop

>>> D = {'a': 1, 'b': 2, 'c': 3}>>> for (key, value) in D.items():… print(key, '=>', value)...a => 1c => 3b => 2

for num in range(10,20): #to iterate between 10 to 20for i in range(2,num): #to iterate on the factors of the number

…. else: # else part of the loop print num

29February 2014Learning Python | Part 2- Chapter 4 | Koosha Zarei

RepetitionIterators

>>> for x in [1, 2, 3, 4]: print(x ** 2, end=' ')...1 4 9 16>>> for x in (1, 2, 3, 4): print(x ** 3, end=' ')...1 8 27 64

for num in range(10,20): #to iterate between 10 to 20for i in range(2,num): #to iterate on the factors of the number

…. else: # else part of the loop print num