Skip to content
Advertisement

How should I validate this correctly?

input1= input("Enter a word or number: ")
input2= input("Enter another word or number: ")
check1= input1.isdigit()
check2= input2.isdigit()
def x(input1, input2):
    if check1== True and check2==True:
        if input1>input2:
            return "The first number is bigger"
        elif input2>input1:
            return "The second number is bigger"
        else:
            return "Both numbers are same size"
        
    elif check1== False and check2== False: 
        for i in input1:
            y=i.isdigit()
            if y== True:
                return "Enter a word or a number"
            else:
                for j in input2:
                    z=j.isdigit()
                    if z== True:
                        return "Enter a word or a number"
                    else:
                        if len(input1)>len(input2):
                            return "The first word is longer"
                        elif len(input1)==len(input2):
                            return "The words are the same length" 
                        else:
                            return "The second word is longer"
    else:
        return "Can't compare"
x(input1, input2)
y = x(input1, input2)
print(y)

”’ This is a function which asks the user to input two values and then gives the longer word if the user inputs two words or gives the bigger number when the user enters two numbers. It returns can’t compare if the user enters a word and a number, however the problem I am facing is I am unable to validate when the user enters something like Ml3003322 or qwewe9qw92222. Could anyone suggest possible solutions? ”’

Advertisement

Answer

You are looking for isalpha and isdecimal to test if a given string contains all letters or digits.
Uasge example:

def is_word_number(s):
    if s.isalpha():
        return 'word'
    if s.isdecimal():
        return 'number'
    return 'error'
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement