0

Currently I'm studying on for loops and I've been given an assessment to get a better grab of it which was asking for me to printing only the words starting with 's' in the following string

st = 'Print only the words that start with s in this sentence'

and I wrote that simple codeline to get the job done

for word in st.split():
    if word[0] == 's' or 'S':
        print (word)

which resulted in following output

Print
only
the
words
that
start
with
s
in
this
sentence

The point couldn't grasp on is if I use and operator between 's' and 'S' or don't even use and operator between them (by demolishing 'S' of course.) instead of 'or' operator. I get the desired result which is:

start
s
sentence

Any ideas why is this happening and how I failed to understand the difference between them would be very much appreciated

Yekta Aktaş
  • 125
  • 1
  • 9
  • 1
    `if word[0] == 's' or word[0] == 'S'`: – Devesh Kumar Singh Jul 04 '19 at 13:32
  • 1
    Try `if word[0] == 's' or word[0] == 'S':` – Arkistarvh Kltzuonstev Jul 04 '19 at 13:33
  • 1
    The issue here appears to be that the string literal `'S'` is evaluating to true. Therefore, ti doesn't even matter what the first letter is, because the boolean expression would always be true. I'm not sure if Devesh's duplicate link is appropriate here. – Tim Biegeleisen Jul 04 '19 at 13:34
  • @TimBiegeleisen Yes, now I see that was the main issue but I literally have no idea why it has happened and how can I use this codeline with my desired 'S' outputs – Yekta Aktaş Jul 04 '19 at 13:37
  • @YektaAktaş Read the very first comment under your question `:-)` – Tim Biegeleisen Jul 04 '19 at 13:41
  • @TimBiegeleisen tjx, I see now strings themself considered to be true so my codeline printed out every single word instead of what I am looking for – Yekta Aktaş Jul 04 '19 at 13:43
  • Yeah...it's an insidious bug actually, because in many (most?) other programming languages, such syntax would not even compile. Python, being a scripting language, is a bit more forgiving and allows the script to run (albeit not with the logic you really want). – Tim Biegeleisen Jul 04 '19 at 13:44

0 Answers0