I'm trying to make a simple random name generator by pulling first and last names from text files. The problem I'm having is that sometimes the names are chopped off and incomplete with the output and sometimes the names are on two different lines.

I would also like to be able to make it loop such that you could press enter to get a new random name right below the first, but I'm not sure how to do that.

    import random

    a = random.randint(1, 10)
    b = random.randint(1, 10)
    space = ' '

    f = open('fname.txt')
    inFile = open('fname.txt')
    fname = f.readline(a)
    f.close()

    f = open('lname.txt')
    inFile = open('lname.txt')
    lname = f.readline(b)
    f.close()

    print (fname + space + lname)

    raw_input()

no need to open and close the file several times. for names printing in different lins you can strip the end of line symbol. a simple function is what I would use:

import random

def name_gen()
    query = raw_input("Whould you like to generate a random name? y/n")
    if query == "y" 
        a = random.randint(1, 10)
        b = random.randint(1, 10)
        first_name = open ( 'fname.txt' ).readline(a).strip("\n") 
        last_name = open ( 'lname.txt' ).readline(b).strip("\n")
        print(first_name, last_name)
        name_gen()

name_gen()

there are more solutions that far more expert people here can provide. so condider this post as one option from a novice that I am.
btw, I have not tested this and just posted it as it came to my mind :D

sorry for the typo. please correct line 5 like this:

if query == "y":

The code you suggested spits out a syntax error warning and puts a big red bar on all the code. I can't find anything wrong with the code though, and the big red bar doesn't help me.

http://puu.sh/11UaS

I can't seem to edit my previous post, so I'll just make a new one.

I tried this:

import random

a = random.randint(1, 10)
b = random.randint(1, 10)

first_name = open ('fname.txt').readline(a).strip("\n")
last_name = open ('lname.txt').readline(b).strip("\n")

print(first_name, last_name)

raw_input()

But, it still clips off the ends of names, and running it more than once in the same instance of the python shell produces no output.

I believe the code only reads the first line in each text file and the variables a and b are being used as an indicator for the number of characters to be pulled from the first line instead of which line should be pulled in full.

This is not the most efficient or tight code, but it works. In particular, the function populate(...) could be shorter. In a real world situation populate() should raise a useful error if the files aren't found or aren't as expected (many more lines of code)

I have also deliberately made the output print incorrectly unless you are using Python 3. Note also that raw_input would be incorrect with Python 3.

I've broken the work into two functions and a driver loop. This is typical style for interactive programs; though usually the driver loop is also in its own function which is called from the bottom of the file.

import random
def populate(first_file_name, last_file_name):
    first_names = []
    last_names = []
    with open(first_file_name,'r') as f:
        for line in f:
            first_names.append(line.strip())
    with open(last_file_name,'r') as f:
        for line in f:
            last_names.append(line.strip())
    return first_names, last_names

def print_random_name(first_names,last_names):
    if not first_names:
        first_names = ['Henry']
    if not last_names:
        last_names = ['Jones']
    print(random.choice(first_names), random.choice(last_names))

first_names, last_names = populate('fname.txt','lname.txt')

response = 'y'
while response == 'y':
    print_random_name(first_names,last_names)
    response = raw_input('Print another? ').lower()[0]

Thank you based griswolf. This really helps me, as I can look at this little script's use of functions when I come up with more ideas of things to make.

I went ahead and changed raw_input() to input() so it would work with python 3.

Edit: How can I get the script to do something different if the response is different? I want it to close if the response is n.

I tried this but it doesn't work:

import random
import sys

def populate(first_file_name, last_file_name):
    first_names = []
    last_names = []
    with open(first_file_name, 'r') as f:
        for line in f:
            first_names.append(line.strip())
    with open(last_file_name, 'r') as f:
        for line in f:
            last_names.append(line.strip())
    return first_names, last_names

def print_random_name(first_names, last_names):
    if not first_names:
        first_names = ['Henry']
    if not last_names:
        last_names = ['Jones']
    print(random.choice(first_names), random.choice(last_names))

first_names, last_names = populate('fname.txt', 'lname.txt')

response = 'y'
while reponse == 'y':
    print_random_name(first_names, last_names)
    response = input('Print another? ').lower()[0]

if response == 'n':
        sys.exit(1)
  1. You need to understand the with statement at my lines 5 and 8: not more important than def, but less likely to be covered in an intro course.

  2. You need to understand how to read the python manual: http://docs.python.org/index.html so as to make best use of the library features. You tried to use randint which is not best suited to this problem. It is mostly a matter of searching and then reading more than just a little bit.

  3. I don't understand "close". I suspect you're using Python in an environment other than the command line. I just use the command line so I'm not the person to ask about how to deal with your environment.

  4. In passing, the Python style guide: Indentation calls for using 4 spaces per indent level. It is very good to just grit your teeth and follow the style guide even if you have a different preference: It is practical, well thought out, everybody understands how to read it (and code reading happens much more than code writing). In particular, because tabs and spaces look the same on the screen, don't ever mix them, but to conserve screen space (width) do prefer spaces alone. Your editor will have a setting to help make that happen.

Thank you again griswolf!

I'll be looking through the python manual to find out how to do the things I'm trying to do, and I'll be sure to make that coding style guide a firm habit once I get a look at it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.