Python Checking 4 digits

Question:

import string
import math
def fourDigit():
    num = raw_input("Enter a 4 digit number: ")
    if (len(num) == 4 and string.digits == True):
        some = int(int(val[1]) + int(val[3]))
        print("The sum of the 1st and second term is: ")
    else:
       print("Error!")

So in this function I specified that the number must be 4 digits and the string must have digits. Even if i enter 1234 it prints error.

Asked By: Jefa

||

Answers:

string.digits is a string, "0123456789". string.digits == True is nonsensical, and guaranteed to always return False.

If you’re trying to make sure all the characters entered are numeric, do:

if len(num) == 4 and num.isdigit():

If you really want to use string.digits for whatever reason, a slower approach that uses it correctly would be:

if len(num) == 4 and all(c in string.digits for c in num):
Answered By: ShadowRanger
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.