Book Image

Getting Started with Python and Raspberry Pi (Redirected from Learning Python By Developing Raspberry Pi Applications)

By : Dan Nixon
Book Image

Getting Started with Python and Raspberry Pi (Redirected from Learning Python By Developing Raspberry Pi Applications)

By: Dan Nixon

Overview of this book

Table of Contents (18 chapters)
Getting Started with Python and Raspberry Pi
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Control flow operators


If you have ever used any other programming language, you are probably familiar with the standard control flow operators if, for, and while, which are all present in Python and operate in a fairly similar way.

if and while can be used in a similar way as they would usually be with any Boolean expression, as shown in the following example. Since the interactive terminal is not fantastic at handling indentation, we will just run these examples as standard Python scripts.

import random
if random.randint(1, 100) % 2 == 1:
    print "Win!"
else:
    print "Lose!"
times_lost = 0
while random.randint(1, 100) % 2 == 0:
    times_lost += 1
print "Win! (after %d losses)" % (times_lost)

As the following output shows, the execution in the first example is controlled solely by the random number generated in the if statement. In the second, the random number generation determines the amount of times a section of code will be executed whilst the overall control flow stays constant...