I just started to learn Python, and wrote this Madlib program that works the way I intended it to, so I do not need help debugging, just some advice on tips to improve the code or make it simpler.

#Date 8SEP14

#introduction and file select

from os import listdir
for each in listdir():
if each.endswith('txt'):
print (each)
file_choice = input("What Madlib would you like to do? ")

#if input is not good then repeats until a good input is entered
while file_choice not in listdir():
file_choice = input("Please try again and don't forget the .txt at the end ")

#opening file and setting variables
with open(file_choice,"r",encoding = "utf-8") as my_file:
user_inputs = []
user_inputs_index = []
x = 0
if item in word_types and user_inputs_index == []:
user_inputs.append(item)
else:
if item in word_types:
user_inputs.append(item)
for each in user_inputs:
user_inputs[x] = input("Please Enter a(n) " + each + ": ")
x += 1
z = 0
for word in user_inputs:
y = int(user_inputs_index[z])
z += 1

my_file.close()


One thing I notice here is that you don't follow the DRY principle. Don't Repeat Yourself.

Always make an attempt to not repeat yourself because it a) cuts down on code, b) makes code easier to modify, and c) usually runs more efficiently. for example.

for item in new_read_file:
if item in word_types and user_inputs_index == []:
user_inputs.append(item)
else:
if item in word_types:
user_inputs.append(item)


This function checks item in word_types two times in a row (which is inefficient), and in each case you do user_inputs.append(item) when you would do it regardless (which makes it harder to modify).

Try changing it to:

for item in new_read_file:
if item in word_types:
user_inputs.append(item)
if user_inputs_index == []:

PS instead of writing else: if...: you can simply write elif...: