Reader small image

You're reading from  Getting Started with Python and Raspberry Pi (Redirected from Learning Python By Developing Raspberry Pi Applications)

Product typeBook
Published inSep 2015
Reading LevelBeginner
Publisher
ISBN-139781783551590
Edition1st Edition
Languages
Right arrow
Author (1)
Dan Nixon
Dan Nixon
author image
Dan Nixon

Dan Nixon is a software and electronics engineer living in the north of England. He has past experience of creating software for data analysis, process control, and business intelligence applications. In most of these projects, Python was one of the main languages used. Dan previously authored another book on the uses of the Raspberry Pi, called Raspberry Pi Blueprints, and has worked on many personal projects that use both Python and the Raspberry Pi.
Read more about Dan Nixon

Right arrow

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...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Getting Started with Python and Raspberry Pi (Redirected from Learning Python By Developing Raspberry Pi Applications)
Published in: Sep 2015Publisher: ISBN-13: 9781783551590

Author (1)

author image
Dan Nixon

Dan Nixon is a software and electronics engineer living in the north of England. He has past experience of creating software for data analysis, process control, and business intelligence applications. In most of these projects, Python was one of the main languages used. Dan previously authored another book on the uses of the Raspberry Pi, called Raspberry Pi Blueprints, and has worked on many personal projects that use both Python and the Raspberry Pi.
Read more about Dan Nixon