I'm working on a project for university, and I need to use an integer from a user input. However I'm trying to make sure my code doesn't break as soon as someone types something the code wasn't expecting, a letter or word instead of a number for example.
After asking, I was told I'm not to use isdigit()
or similar functions. Is there a way out of this or should I ignore this weak point in my code?
CodePudding user response:
Technically this doesn't use any functions like isdigit()
...
all(c in "0123456789" for c in string)
Examples:
>>> string = "239a0932"
>>> all(c in "0123456789" for c in string)
False
>>> string = "9390239"
>>> all(c in "0123456789" for c in string)
True
CodePudding user response:
You can either just try to convert the input to an int, and if it fails with an exception, it wasn't a number. Or you use a regular expression.
import re
entered = input("Enter a text: ")
# Check as regular expression
pattern = re.compile(r"^\d $")
if pattern.match(entered):
print("re says it's a number")
else:
print("re says it's not a number")
# Try to convert
try:
asNum = int(entered)
print("can be converted to a number")
except ValueError:
print("cannot be converted to a number")
CodePudding user response:
Use try
/except
:
try:
num = int(input("Enter a number"))
except ValueError:
# do whatever you want to do if it wasn't a valid number
If you want to re-prompt the user until they enter a number, and then go ahead with whatever you needed num
for, that looks like:
while True:
try:
num = int(input("Enter a number"))
break # end the loop!
except ValueError:
print("nope, try again!")
# loop continues because we didn't break it
print(f"{num} {num} = {num * 2}!")
CodePudding user response:
For example:
if len(my_probably_digits_str) == len("".join([x for x in my_probably_digits_str if x in "0123456789"])):
print("It's convertable!")