Python – 随机婴儿名称生成器问题 – (重复输入,调用变量)

我整个下午都在看这个问题,并且无法弄清楚为什么性别输入会重复出现,尽管只是被称为一次.它也不是我能看到的循环的一部分.

我已经尝试添加变量来充当计数器并尝试使用if语句仅在计数器变量小于1时运行输入,但无法弄清楚.

编辑:由于这里的反馈很好,我发现get_full_name导致get_first_name中的重复性别输入 – 但是现在我在尝试输出随机生成的第一个&中间名.

我想把setFirst,setMiddle和setLast变量设置为全局变量,但后来我得到一个NameError.我也尝试创建一个新功能来显示它们,但那也没有用.我尝试添加“自我”. (不带引号)直接在function()或其下面的一个缩进中.

我将首先显示错误,然后显示完整代码.

错误:
    Traceback(最近一次调用最后一次):
      文件“init.py”,第100行,in
        主要()
      在主文件中输入“init.py”,第92行
        print displayName(setFirst,setMiddle,setLast)
    NameError:未定义全局名称“setFirst”

尝试将setFirst,setMiddle和setLast连接到另一个全名变量时,我也会收到名称错误.

这是代码:

from os.path import abspath, join, dirname
import random

full_path = lambda filename: abspath(join(dirname(__file__), filename))


FILES = {
    'first:male': full_path('dist.male.first'),
    'first:female': full_path('dist.female.first'),
    'last': full_path('dist.all.last'),
}


def get_name(filename):
    selected = random.random() * 90
    with open(filename) as name_file:
        for line in name_file:
            name, _, cummulative, _ = line.split()
            if float(cummulative) > selected:
                return name


def get_first_name(gender=None):
    global determine
    global setFirst

    print ("First name... Enter 1 for Male, 2 for Female or 3 to be surprised! ")
    determine = input()

    if determine == 1:
        gender = 'male'
    if determine == 2:
        gender = 'female'
    if determine == 3:
        print ("You want to be surprised!")
        gender = random.choice(('male', 'female'))

    return get_name(FILES['first:%s' % gender]).capitalize()
    setFirst = get_first_name()
    print setFirst + " "

def get_middle_name(gender=None):
    global setMiddle

    if determine == 1:
        gender = 'male'
    if determine == 2:
        gender = 'female'
    if determine == 3:
        gender = random.choice(('male', 'female'))

    return get_name(FILES['first:%s' % gender]).capitalize()
    setMiddle = get_middle_name()
    print setMiddle + " "

def get_last_name():
    global setLast

    #We will implicitly pass a Last Name until other issues are fixed
    return “Smith”

    setLast = get_last_name()
    print setLast

def get_full_name(gender=None):
    return u"%s %s %s" % (get_first_name(gender), get_middle_name(gender), get_last_name())

#def displayName(setFirst, setMiddle, setLast):
#    print setFirst + " " + setMiddle + " " + setLast

def main():
    #print u"%s %s %s" % (setFirst, setMiddle, setLast)
    #print displayName(setFirst, setMiddle, setLast)

    f = open('output', 'a') #append output to filename output
    f.write(get_full_name() + '\n') #and add a line break after each run
    f.close()

if __name__ == "__main__":
    main()

即使我尝试将变量传递给main(),例如:

def main(setFirst, setMiddle, setLast):

它仍然提供关于未定义的NameError.我究竟做错了什么?

我在“import random”下添加了这个权利,但是现在我得到一些流氓“无”显示 – 这让我相信代码中的某个地方有泄漏.思考?

setFirst = None
setMiddle = None
setLast = None

这是我创建的用于尝试跟踪它的函数:
def displayName(setFirst,setMiddle,setLast):

if setFirst == None:
    print ("Random Baby Name Generator")

else:
    print setFirst
    print setMiddle
    print setLast

if setMiddle == None:
    print ("Double check the middle name variable.")

if setLast == None:
    print ("Double check the last name variable.")

最佳答案 您正在调用get_full_name()两次,您需要保存结果:

def main():
    full_name = get_full_name()
    print(full_name)
    f = open('output', 'a') #append output to filename output
    f.write(full_name + '\n') #and add a line break after each run
    f.close()

你也有一些缩进问题,加上你使用全局变量有点效率低下.理想情况下,功能应该只执行一项任务;这使它们更容易调试.

试试这个不同版本的代码:

from os.path import abspath, join, dirname
import random

full_path = lambda filename: abspath(join(dirname(__file__), filename))


FILES = {
    'first:male': full_path('dist.male.first'),
    'first:female': full_path('dist.female.first'),
    'last': full_path('dist.all.last'),
}

GENDER_MAP = {'1': 'male', '2': 'female'}

def get_gender():
    result = input('Select a gender: 1 for Male, 2 for Female or 3 to be surprised')
    if result not in ('1', '2', '3'):
       print('{} is not a valid choice, please try again'.format(result))
       return get_gender()
    if result == '3':
       return random.choice(('1', '2'))
    return result

def get_name(filename):
    selected = random.random() * 90
    with open(filename) as name_file:
        for line in name_file:
            name, _, cummulative, _ = line.split()
            if float(cummulative) > selected:
                return name

def get_name_from_file(name_type='first', gender='male'):
    if name_type in ('first','middle',):
        name = get_name(FILES['{}:{}'.format(name_type, gender)]).capitalize()
    else:
        name = get_name(FILES['last']).capitalize()
    return name

def get_full_name():
    gender = get_gender()
    gender_file = GENDER_MAP.get(gender, '')
    first_name = get_name_from_file('first', gender_file)
    middle_name = get_name_from_file('middle', gender_file)
    last_name = get_name_from_file('last')

    return '{} {} {}'.format(first_name, middle_name, last_name)

if __name__ == '__main__':
    name = get_full_name()
    print(full_name)
    with open('output', 'a') as f:
       f.write('{}\n'.format(full_name))
    print('Done')
点赞