Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function does not print the randomness of two other functions. NameError: the name 'x' is not defined

I have a problem with the All function. I would like to use the random result of the Template1 function and the random result of the Template2 function. Then I apply another random to the two functions inside All, but I get the error:

NameError: the name 'Template1' is not defined

How can I fix? By solving the definition, will the script print correctly what I asked? Thank you

The output I would like to receive is only one (1) of these: "aaa", "bbb", "ccc", "ddd", "eee", "fff"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import random

class Main:

    def __init__(self):
        self.templ1 = ("aaa", "bbb", "ccc")
        self.templ2 = ("ddd", "eee", "fff")
                
    def Template1(self):
        templ1_random = print(random.choice(self.templ1))
        return templ1_random
        
    def Template2(self):
        templ2_random = print(random.choice(self.templ2))
        return templ2_random

    def All(self):
        list0 = [Template1(self), Template2(self)]
        all_random = print(random.choice(list0))
        return all_random

final = Main()
final.All()

>Solution :

Remove all the print() calls from your methods. They’re setting the return variables to None, since print() prints its argument, it doesn’t return it.

To see the result, use print(final.All()) at the end.

import random

class Main:

    def __init__(self):
        self.templ1 = ("aaa", "bbb", "ccc")
        self.templ2 = ("ddd", "eee", "fff")

    def Template1(self):
        templ1_random =random.choice(self.templ1)
        return templ1_random

    def Template2(self):
        templ2_random = random.choice(self.templ2)
        return templ2_random

    def All(self):
        list0 = [self.Template1(), self.Template2()]
        all_random = random.choice(list0)
        return all_random


final = Main()
print(final.All())

DEMO

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading