Seite - 30 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Bild der Seite - 30 -
Text der Seite - 30 -
30 2 BasicConstructions
hold thecoordinatesof apoint and letdbe the lengthof themove. Apseudocode
(i.e., not“real”code, just a“sketchof the logic”) thengoes like
r = random number in [0,1)
if 0 <= r < 0.25
move north: y = y + d
else if 0.25 <= r < 0.5
move east: x = x + d
else if 0.5 <= r < 0.75
move south: y = y - d
else if 0.75 <= r < 1
move west: x = x - d
Note the need for first asking about the value ofr and then performing an action.
If the answer to the “if” question is positive (true), we are done and can skip the
nextelse ifquestions. If theanswer isnegative(false),weproceedwith thenext
question. The last test if 0:75 r < 1 could also read just else, sincewe here
coverall the remainingpossiblervalues.
Theexactcode inPythonreads
import random
r = random.random() # random number in [0,1)
if 0 <= r < 0.25:
# move north
y = y + d
elif 0.25 <= r < 0.5:
# move east
x = x + d
elif 0.5 <= r < 0.75:
# move south
y = y - d
else:
# move west
x = x - d
Weuseelse in the last test to cover the different types of syntax that is allowed.
Pythonrecognizes the reservedwordsif,elif (short forelse if), andelseand
expects thecode tobecompatiblewith the rulesof if tests:
The test reads if condition:, elif condition:, or else:, where
condition is a boolean expression that evaluates to True or False. Note
theclosingcolon (easy to forget!).
If condition is True, the following indented block of statements is executed
and the remainingeliforelsebranchesareskipped.
If condition is False, the program flow jumps to the next elif or else
branch.
The blocks after if, elif, or elsemay contain new if tests, if desired. Regard-
ing colon and indent, youwill see below that these are required in several other
programmingconstructionsaswell.
Workingwith if tests requiresmastering boolean expressions. Here are some
basic boolean expressions involving the logical operators ==, !=, <, <=, >, and
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python
- Titel
- Programming for Computations – Python
- Untertitel
- A Gentle Introduction to Numerical Simulations with Python
- Autoren
- Svein Linge
- Hans Petter Langtangen
- Verlag
- Springer Open
- Datum
- 2016
- Sprache
- englisch
- Lizenz
- CC BY-NC 4.0
- ISBN
- 978-3-319-32428-9
- Abmessungen
- 17.8 x 25.4 cm
- Seiten
- 248
- Schlagwörter
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Kategorie
- Informatik