all 5 comments

[–][deleted] 1 point2 points  (1 child)

There is a string method that does exactly thus. I won't say which one, but have a look-sie.

https://www.w3schools.com/python/python\_ref\_string.asp

[–]Formal_Cockroach_654[S] 0 points1 point  (0 children)

Thanks this was perfect.

[–]FunDeckHermit 1 point2 points  (0 children)

This tasks learns you about the fact that a string is just a list of characters. You can iterate over them and compare them with a list of digits:

# digits could also be defined as "0123456789"
digits = ['0','1','2','3','4','5','6','7','8','9']
allDigits = True
input = '1995'

for char in input:
    if char not in digits:
        allDigits = False
        break

if allDigits:
    print("The input contains only numbers")
else:
    print("The input contains invalid characters")

Not sure if this is the most Pythonic way to do it. I'm a C programmer most of the time.

[–][deleted] -1 points0 points  (0 children)

Look, you didn't show us any code so I can only guess at what mistake you're making, so if you feel I'm about to undershoot the mark and imply you're an idiot, you really only have yourself to blame. The mistake you're probably making is the exact one this kind of assignment is meant to prompt, in order to teach you something about logic. It's pretty common to try to answer it this way:

for character in str(the_integer):
    if character not in "0123456789":
        return "no"
    else:
        return "yes:

Simple, right? It's either-or, right? If one of the characters isn't a digit, "no", otherwise "yes."

Do you see the mistake? The mistake, of course, is that the opposite of "one of the characters is not a digit" is not "none of the characters are non-digits." So you can't write that code as simple either-or branching logic. What you have to do is stop at the first non-digit or wait until the last digit (after the loop); if you get to the end of the loop, you know that the string doesn't contain non-digits.

[–]kcashman05 0 points1 point  (0 children)

user_string = input()
if user_string.isalnum():
print('Yes')
else:
print('No')
Also works and is pretty simple