1

I want to get the result() method's variable that is called word.

If someone knows how to do it, please help me.

def result(self,var1,word="",mainlista=mainlista):
    try:
        for i in range(int(var1)):
            x = random.choice(mainlista)
            word += x
    except IndexError:
        pass
5
  • 8
    The function should return it. Commented Oct 23, 2021 at 15:53
  • 3
    Why do you have try? Nothing in that code can raise IndexError. Commented Oct 23, 2021 at 15:54
  • Or the function could assign x to an instance variable. Commented Oct 23, 2021 at 15:55
  • 1
    Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Oct 23, 2021 at 15:55
  • Please put the complete code Commented Oct 23, 2021 at 16:30

1 Answer 1

3

If you don't want result() to return word you can create an instance variable for it see example below.

import random


mainlista = ['london', 'paris', 'tokyo']


class WordPower:
    def __init__(self, var1, mainlista):
        self.var1 = var1
        self.mainlista = mainlista
        self.word = ''

    def result(self):
        try:
            for _ in range(self.var1):
                x = random.choice(self.mainlista)
                self.word += x
        except IndexError as e:
            print(e)


var1 = 2
a = WordPower(var1, mainlista)
a.result()
word = a.word
print(word)

# tokyoparis

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.