Seite - 92 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 92 -
Text der Seite - 92 -
92 4 FunctionsandtheWritingofCode
print(’\n*** Welcome to the times tables test! ***\
\n (To stop: ctrl-c)’)
# Ask user for a*b, ... a, b are in [1, N]
N = 2
score = 0
for i in range(1, N+1, 1):
for j in range(1, N+1, 1):
user_answer = ask_user(i, j)
score = score + points(i, j, user_answer)
print(’Your score is now: {:d}’.format(score))
print(’\nFinished! \nYour final score: {:d} (max: {:d})’\
.format(score, N*N))
Running theprogram, thedialoguecould, forexample,proceedlike
*** Welcome to the times tables test! ***
(To stop: ctrl-c)
1 * 1 = 1
Correct!
Your score is now: 1
1 * 2 = 2
Correct!
Your score is now: 2
2 * 1 = 3
Sorry! Correct answer was: 2
Your score is now: 2
2 * 2 = 4
Correct!
Your score is now: 3
Finished!
Your final score: 3 (max: 4)
Weseethat thebehavior isasexpected.Again, it is important thatyoureadthecode
andconfirmthatyourunderstandingis in linewith theoutputshown.
Testing forEquality with==
Inourcode,we compare two integers in theif test
if user_answer == true_answer:
Testing for equality with == works fine for the integers we have here.
In general, however, such tests need to account for the inexact number
representation thatwehaveoncomputers.Moreabout this inSect.6.6.3.
Note that thenewcodeimplementedwhenupdatingfromtimes_tables_1.py
totimes_tables_2.py, included the functionbodies in both functionsask_user
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
- Titel
- Programming for Computations – Python
- Untertitel
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Band
- Second Edition
- Autoren
- Svein Linge
- Hans Petter Langtangen
- Verlag
- Springer Open
- Datum
- 2020
- Sprache
- englisch
- Lizenz
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Abmessungen
- 17.8 x 25.4 cm
- Seiten
- 356
- Schlagwörter
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Kategorie
- Informatik