Page - 95 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 95 -
Text of the Page - 95 -
4.2 ProgrammingasaStep-WiseStrategy 95
score = score + points(a, b, user_answer)
print(’Your score is now: {:d}’.format(score))
print(’\nFinished! \nYour final score: {:d} (max: {:d})’\
.format(score, N*N))
Running this code, the order of the questions will be generated anew with each
execution(becauseoftherandomization),but thedialoguemay,forexample,appear
like:
*** Welcome to the times tables test! ***
(To stop: ctrl-c)
5 * 5 = 25
Correct!
Your score is now: 1
5 * 3 = 15
Correct!
Your score is now: 2
9 * 9 = 81
Correct!
Your score is now: 3
...
... <longer printout... author’s comment>
...
Finished!
Your final score: 95 (max: 100)
Great!Ourcodeseems to runsmoothly, sowhat canpossiblygowrongnow?
Thiswill gowrong:
*** Welcome to the times tables test! ***
(To stop: ctrl-c)
3 * 2 = six
Traceback (most recent call last):
...
... < longer printout... author’s comment >
...
ValueError: invalid literal for int() with base 10: ’six’
If a user gives some unexpected input that the code is not prepared to handle,
things can go very wrong! In this case, we get an error message (referring to some
ValueError),sinceourprogramdoesnotunderstandthat“six”actuallymeans the
number6.
It would not be very professional to leave our program with this potential
problem,soitshouldbefixed,buthow?Thegoodnewsisthatmodernprogramming
languages,Pythoninclusive,dohavetherighttools todealwithsuchcases.Fornow,
we will leave our code as it is, but we hereby add yet another step to our program
developmentplan, and will solve the problem when we turn to exception handling
inSect.5.2.Thatwill alsobringus to the fourthversionofourprogram,whichalso
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