Search code examples
python-3.xif-statementatom-editorstring-lengthplatformio

If statement get's a skipped, while only else statement get's printed .And how do I store a string or int in a single variable?


I was trying to do an exercise ,which asked us to solve this following problem Exercise problem image which I tried to do ,but by not using same exact keywords as shown in the exercise.

Here is my code

def StringLength(length_of_String):
    return len(text)

text = input("length_of_String :")

if type(text) == int:
    print ("python doesn't show length of integers")
else :
    print (len(text))

But the problem I get here is , if I add any text say like"joker" . It will output me length as "5",which is correct .

But when I type any integer or float , say "101" , it still prints it length as "3" because it is reading it as a string.

So how come I add Variable in which when I input a integer or string , it should recognise it as a string or an integer


Solution

  • some_variable = input() by default will give you string. You may want to modify your code:

    def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False
    
    def StringLength():
        text = input('Enter:')
        if is_number(text):
            print ("python doesn't show length of integers")
        else :
            return(len(text))
    
    #StringLength() #Remove the '#' at the start of the line to test the function
    

    Edit: I have added a function to test if the entered value is a number or not