1

I am beginner programmer in python and i dont know why the input of this code isnt as i expect it to be:

my input

I am beginner programmer in python and i dont know why the input of this code isnt as i expect it to be:

def count_smileys(arr):
    #the number of valid smiley faces in array/list
    smileys_count = 0
    for character in arr:
        if len(character) == 2:
            if character[0] == ":" or character[0] == ";" and character[2] == ")" or character[2] == "D":
                smileys_count += 1
        if len(character) == 3:
            if character[0] == ":" or character[0] == ";" and character[2] == ")" or character[2] == "D" and character[2] == "-" or character[2] == "~":
                smileys_count +=1

    return(smileys_count)

and the output is this :

my output

rdas
  • 20,604
  • 6
  • 33
  • 46
Doomes
  • 25
  • 2

2 Answers2

1

You missed parenthesis, when you mix in a sentence AND/OR, you usually need parenthesis:

def count_smileys(arr):
    #the number of valid smiley faces in array/list
    smileys_count = 0
    for character in arr:
        if len(character) == 2:
            if (character[0] == ":" or character[0] == ";") and (character[1] == ")" or character[1] == "D"):
                smileys_count += 1
        if len(character) == 3:
            if (character[0] == ":" or character[0] == ";") and (character[1] == ")" or character[1] == "D") and (character[2] == "-" or character[2] == "~"):
                smileys_count +=1

    return(smileys_count)

Also, your indexes are wrong

nacho
  • 5,280
  • 2
  • 25
  • 34
  • No they are not wrong i just wrote them in weird order because the character - and ~ are in the middle of the string if strings len is 3 – Doomes Oct 04 '19 at 19:44
1

It's the logical operator precedence problem: and has a higher priority than or, much like * has a precedence over +. You should use parentheses.

if len(character) == 2:
  if (character[0] == ":" or character[0] == ";") and (character[1] == ")" or character[1] == "D"):
    smileys_count += 1

etc.

See also Priority of the logical statements NOT AND & OR in python.

Igor F.
  • 2,649
  • 2
  • 31
  • 39