Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
For loop issues
#2
(Feb-12-2018, 04:29 PM)BigEasy Wrote:
        for x in s1:
            for y in s2:
                if y != x:
                    count += 1
            #return count
             
            if count < 2:
                return 1
            else:
                return 2

You are looping through each character in both strings, but you're probably not doing what you expect. You compare the first character of the first string against every character in the second string. And then you return, without ever getting to the second character of the first string.

As a demonstration, here's what you're doing, with print functions added:
>>> first = 'spam'
>>> second = 'eggs'
>>> for char in first:
...   for compare in second:
...     print("{0} == {1} => {2}".format(char, compare, char==compare))
...   break
...
s == e => False
s == g => False
s == g => False
s == s => True
What you probably want to do, is use indexing instead of looping over the string itself. That way, you're comparing characters at the same positions in each string. Something like:
>>> first = 'spam'
>>> second = 'eggs'
>>> for ndx, ch in enumerate(first):
...     print("{0} == {1} => {2}".format(ch, second[ndx], ch==second[ndx]))
...
s == e => False
p == g => False
a == g => False
m == s => False
Reply


Messages In This Thread
For loop issues - by BigEasy - Feb-12-2018, 04:29 PM
RE: For loop issues - by nilamo - Feb-12-2018, 05:08 PM
RE: For loop issues - by BigEasy - Feb-12-2018, 05:52 PM
RE: For loop issues - by nilamo - Feb-12-2018, 06:10 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Having issues getting a loop to work PLESSE HELP ASAP manthus007 1 2,162 Aug-25-2018, 10:44 AM
Last Post: j.crater

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020