Page - 92 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 92 -
Text of the Page - 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, Volume Second Edition
- Title
- Programming for Computations β Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik