Home > front end >  Function does not print the randomness of two other functions. NameError: the name 'x' is
Function does not print the randomness of two other functions. NameError: the name 'x' is

Time:11-19

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"

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()

CodePudding user response:

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

CodePudding user response:

Change list0 = [Template1(self), Template2(self)] to [self.Template1(), self.Template2()]

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())
  • Related