Page - 108 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 108 -
Text of the Page - 108 -
108 5 SomeMorePythonEssentials
between different kinds of exceptions, coding a dedicated response in each case.
That can be done in Python,1 and it will also allow us to get back the Ctrl-c
functionality thatwehad in the earlierversions.
A More Detailed Use of try-except We let the final version of our code
(times_tables_4.py) serve as an example of a more refined try-except
construction.It is still simple,buthaswhatweneed.Wepresent thisfinalversionin
its completeness, before explaining the details. All code changes are still confined
to themainpartof theprogram:
import numpy as np
def ask_user(a, b):
"""Get answer from user: a*b = ?"""
question = β{:d} * {:d} = β.format(a, b)
answer = int(input(question))
return answer
def points(a, b, answer_given):
"""Check answer. Correct answer gives 1 point, else zero"""
true_answer = a*b
if answer_given == true_answer:
print(βCorrect!β)
return 1
else:
print(βSorry! Correct answer was: {:d}β.format(true_answer))
return 0
print(β\n*** Welcome to the times tables test! ***\
\n (To stop: ctrl-c)β)
N = 10
NN = N*N
score = 0
index = list(range(0, NN, 1))
np.random.shuffle(index) # randomize order of integers in index
for i in range(0, NN, 1):
a = index[i]//N + 1
b = index[i]%N + 1
try:
user_answer = ask_user(a, b)
except KeyboardInterrupt:
print(β\nOk, you want to stop!β)
break
except ValueError:
print(βYou must give a valid number!β)
continue # jump to next loop iteration
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))
1 https://docs.python.org/3/tutorial/errors.html.
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