pallupz
pallupz

Reputation: 883

Scope of variables in Python when using for loop

I am a newbie to Python (and to programming in general). I have been trying to learn it by trial and error and have run into an issue.

The code I am trying to implement is to get the longest substring which is in alphabetical order. That is,

The code I have written is as below:

s = 'abbcdabcd'
sub = ''
temp = '' 

for index in range(len(s)):
    temp = s[index]
    for i in range(len(s[index:])):
        if index+i+1 < len(s):
            if s[index+i+1] < s[index+i]:
                break
            else:
                temp += s[index+i+1]

    if len(temp) >= len(sub):
        sub == temp

print('final ',sub)

This might not be the optimal logic to implement for this but it seems to be working. Issue is, the final print statement keeps printing the initial value of sub variable. How do I overcome this?

PS: For the above purpose, if there is a better algorithm I can use, please feel free to share that in comments. However, that is only a secondary thing for me now.

Upvotes: 2

Views: 1469

Answers (1)

ajax992
ajax992

Reputation: 996

You are saying that

sub == temp

Remember that the "==" operator is for comparison, NOT for assignment. You are comparing sub and temp instead of assigning. Use

sub = temp

Upvotes: 2

Related Questions