Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String comparison in python not working inside the function

can someone explain me why the equality operator is not working inside this function?

def count_words(words_to_insert, word):

    counter = 0
    
    for i in range(0,words_to_insert):
        random_word = input("Insert a string ")
        
        print(random_word)
        print(random_word == word)
        
        if(random_word == word):
            counter +=1
            print(counter)
    
    return "You inserted the word " + word + " " + str(counter) + " times"

count_words(2, "mango")

enter image description here

If I write two strings outside the function with the same values and I compare them, the result is True

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

string_one = "mango"
string_two = "mango"
string_one == string_two

OUT

True

>Solution :

Do not type " when inputting:

>>> Insert a string "mango"
>>> "mango"
>>> False
>>> Insert a string mango
>>> mango
>>> True
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading