0

I try to write a code that generate random name + random height into dictionary

import random

lst = {}

def adding(num = 5):
    
        first = ("Super", "Retarded", "Great", "Sexy", "Vegan", "Brave", "Shy", "Cool", "Poor", "Rich", "Fast", "Gummy", "Yummy", "Masked", "Unusual", "MLG", "Mlg", "lil", "Lil",)
        second = ("Coder", "Vegan", "Man", "Hacker", "Horse", "Bear", "Goblin", "Learner", "Killer", "Woman", "Programmer", "Spy", "Stalker", "Spooderman", "Carrot", "Goat", "Quickscoper")
        
        
        for i in range(num):    
            random_name = random.choice(first) + " " + random.choice(second)
            random_height = random.randint(135,170)
            lst.update({random_name:random_height})

but i have some problem that when i called function, instead of generate new name, it generate the same name and change the value of height. i need to put a lot of number in parameter (adding(5000)), to generate every name that possible.

so i try to write a code that check which name already is in dictionary. If it already in dictionary, continue a while loop and random name again until it generate new name.

import random

lst = {}

def adding(num = 5):
    
        first = ("Super", "Retarded", "Great", "Sexy", "Vegan", "Brave", "Shy", "Cool", "Poor", "Rich", "Fast", "Gummy", "Yummy", "Masked", "Unusual", "MLG", "Mlg", "lil", "Lil",)
        second = ("Coder", "Vegan", "Man", "Hacker", "Horse", "Bear", "Goblin", "Learner", "Killer", "Woman", "Programmer", "Spy", "Stalker", "Spooderman", "Carrot", "Goat", "Quickscoper")
        
        for i in range(num):
            
            while True:
                global random_name
                random_name = random.choice(first) + " " + random.choice(second)
                if random_name in lst == True:
                    continue
                elif random_name in lst == False:
                    break
            
            random_height = random.randint(135,170)
            lst.update({random_name:random_height})

the problem is these block of while loop doesn't work somehow, and i can't figure out what's wrong with it

  • Replace all your `if`s inside `while` with: `if random_name not in lst: break`. – Austin Aug 05 '20 at 05:01
  • The immediate problem is that you are checking if `random_name` is `in lst == True` which evaluates to `in False`. This is a common FAQ about precedence. But there is a number of oddities in your new code, too; why do you declare a `global`? – tripleee Aug 05 '20 at 05:02

0 Answers0