mardi 26 octobre 2021

Practicing with if/else does not yield expected output [duplicate]

I am following an introductory Python course, but I got stuck practicing with conditions.

The code I am playing with should return the character length of any piece of text you input. If the input consists of non-string data like integers or floats, it coerces these into a string before returning the input length. This part appears to work fine.

However, if the text is already a string, the IF-condition is not met. Hence I expected it to jump straight to ELSE and print the text: "This is a string" in addition to returning the length of 6. But it returns only 6, no printout:

 def length_text(text):
    if text != str:
        text = str(text)
    else:
        print("This is a string")
    return len(text)

length_text("string")

I also tried specifying more clearly what I want with ELIF: if a is not the case and b is the case, print the text and return the length. I even verified that my input "string" is really a string (and it is)! But here, it does not output anything at all:

def length_text(text):
    if text != str:
        text = str(text)
    elif text == str:
        print("This is a string")
    return len(text)

x = "string"
type(x)

length_text(x)

I must have given it the wrong instructions, but I can't wrap my mind around what I need to change. Any help would be much appreciated!

Aucun commentaire:

Enregistrer un commentaire