[Tutor] Try Exclude and operators
Alan Gauld
alan.gauld at yahoo.co.uk
Mon Dec 18 18:18:36 EST 2023
On 18/12/2023 19:18, Matt Athome via Tutor wrote:
> Purpose
> Give test score for input between 0.0 to 1.0
> Use the try and exclude to throw up a message for invalid user input.
I assume this should read try/except not exclude?
> code gives the following error.
> score >= 0 and <= 1.0
> ^^
> SyntaxError: invalid syntax
As the error says that is not valid Python.
The normal way to write the test in a programming language would be:
score >= 0.0 and score <= 1.0
But python has a special syntax for these kinds of comparisons:
0.0 <= score <= 1.0
In both cases the line will evaluate to a boolean True or False.
Neither of these will raise an error for the except to catch.
Normally it would be used inside an if or while statement.
if not 0.0 <= score <= 1.0:
raise ValueError("Score must be between 0 and 1)
And now you can wrap that in a try/except to catch
any errors:
try:
score = float(....)
if not 0.0 <= score <= 1.0:
raise ValueError("Score must be between 0 and 1)
except ValueError:
print(value error message)
> # Score between 0.0 and 1.0
> score = float(input("Enter Score: "))
> try:
> score >= 0 and <= 1.0
> except:
> print("Enter a score between 0.0 and 1.0")
> quit()
That would be a very confusing message since the program
quits. It might be better to report that the given score
was not in the correct range rather than saying Enter
another score.
Alternatively put the input statement into a loop:
while True:
score = float(...)
if 0.0 <= score <= 1.0:
break. # score is good
print(error message here....)
But that doesn't use try/except!
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list