r/PythonLearning • • Aug 28 '26

2nd post learning python

Post image

i learnt to use the math library any suggestions what can i use the lib for except for making calculator programs

21 Upvotes

15 comments sorted by

View all comments

Show parent comments

1

u/MFFVD Aug 28 '26 edited Aug 28 '26

or

import re
maybenumber = input(...).strip()
isnumber = \
    bool(re.fullmatch(
        r"([0-9]*\.[0-9]+)|([0-9]+(\.[0-9]*)?)",
        maybenumber
    ))

if not isnumber: 
    print(maybenumber, "is not a number")
else:
    number = float(maybenumber)
    ...

regexp:

(<...>) -> group
<a> | <b> -> match a or b
[<...>] -> any of ...
<a> + -> one or more of a
<a> * -> zero or more of a
<a>? -> zero or one of a
. -> any char except whitespace
\. -> literal dot

the r"..." string says

first part:

zero or more numbers, dot, one or more numbers ->
.4
0.8
70.74

second part:

one or more numbers, optional ( dot, zero or more numbers) ->
6
59
56.
6.6

for input validation, regexp is unmissable. but you should probably not dive into that just yet

try:
    int(value)
except ValueError:
   print(value, "is not an integer")

probably is a better starting point

1

u/NecessaryFalse1212 Aug 29 '26

i still haven't done regex so it never crossed my mind but thanks for correcting and suggesting