2.5 Exercises
57
In [1]: x = 1; print(x + 1); x = x + 1; x += 1; x = x - 1; x -= 1
In [2]: print(x)
Then type it in and confirm that your predictions are correct.
b) Repeat the previous task, but this time without statements number 3 and 4
(counted from left) of the first input line. To confirm your prediction this time,
use the command history facility to first bring up the previous command line,
which you then edit appropriately before pressing enter.
Remarks With our statements here, it would clearly have been more readable to
write them on separate lines (also making the semi-colon superfluous). Generally,
this is also the case, although the possibility of writing several statements on a single
line comes in handy from time to time.
Exercise 2.5: Boolean Expression—Even or Odd Number?
Let x be an integer. Use the modulo operator and suggest a boolean expression that
can be used to check whether that integer is an even number (or odd, since if not
even, the integer is odd). Then check your suggestion interactively, e.g., for x being
1, 2, 3 and 4.
Exercise 2.6: Plotting Array Data
Assume four members of a family with heights 1.60 m, 1.85 m, 1.75 m, and 1.80 m.
Next door, there is another family, also with four members. Their heights are 0.50 m,
0.70 m, 1.90 m, and 1.75 m.
a) Write a program that creates a single plot with all the heights from both families.
In your code, use the zeros function from numpy to generate three arrays, two
for keeping the heights from each family and one for “numbering” of family
members (e.g., as 1, 2, 3 and 4). Let the code overwrite the zeros in the arrays
with the heights given, using appropriate assignment statements. Let the heights
be presented as two continuous curves in red and blue (solid lines), respectively,
when the heights of each family are plotted against family member number. Use
also the axis function for the plot, so that the axis with family member numbers
run from 0 to 5, while the axis with heights cover 0 to 2.
b) Suggest a minor modification of your code, so that only data points are plotted.
Also, confirm that your suggestion works as planned.
Filename: plot_heights.py.
Exercise 2.7: Switching Values
In an interactive session, use linspace from numpy to generate an array x with
the numbers 1.0, 2.0 and 3.0. Then, switch the content of x[0] and x[1], before
checking x to see that your switching worked as planned.
Filename: switching_values.py.
Précédent

- 79/350

Suivant