pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
You did not use try..except. Eval is unsafe, you can make the computer format your hard disk for example, if you know how. That is why the user input should be checked for correctness. Now you are taking tuple of values, but you should refactor that out of the checking function and input with correct range one by one announcing the user the acceptable range.
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
try:
# processing possibly causing exception
except NameError:
print('You must input strings like this: "my string"')
else:
# code after possible exception point
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
You can code your own check using Python's isdigit() function, but as we have no way of knowing what you have studied in class, you will probably just come back and say that you haven't used it in class, so it would be a further waste of time.
def int_check(str_in):
for ch in str_in:
if ch < "0" or ch > "9":
return False, str_in
return True, int(str_in)
for test_input in ["123", "AString", "123.45"]:
ret, num = int_check(test_input)
if ret:
print num, "IS an integer"
else:
print num, "is NOT an integer"
Note that this is the only code that I will post. If you come back and say "I don't like that" then I will say that you are on your own and will have to provide some code/effort yourself as your original question did not state any limitations, so don't expect us to keep coming back with option after option like a performing seal until you find one that you like,
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
Correct, woooeee. Only you wasted your effort in obfuscating, as OP knows is_digit() allready and is using it. He is only hitting himself to feet trying to check tuples not individual values from user. Here my version, as OP probably has not learned tertiary if also :icon_evil:
for test_input in ["123", "AString", "123.45"]:
print test_input, "IS an integer" if test_input.isdigit() else "is NOT an integer"
OP: the problem is not Python expressions, it is that you are not testing user inputs one by one. I took you not wanting to use int() function, but eval, not about try..except which you should use for robust code in any case.
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852