Jefa
Jefa

Reputation: 45

Python Checking 4 digits

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.

Upvotes: 2

Views: 14953

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155363

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):

Upvotes: 7

Related Questions