I am writing a hangman game where user has possibility to choose between premade list of words to guess or create his own list of words. Later on the program will automatically choose word to guess. Part of the code which causes problem is here:
question_choice = input("Would you like to guess from premade list or to create your own list of words? Please write premade or own: ")
if question_choice == "premade":
print(premade_list[quest])
if question_choice == "own":
length_of_list = int(input("Number of words in your list: "))
for i in range(0, length_of_list):
words = input("Your words: ")
user_list.append(words)
When I choose "own" to create my own list it goes well. But when I choose "premade" - the premade list - the program returns error related to var length_of_list, as below:
"NameError: name 'length_of_list' is not defined"
I surely understand that it is caused by the fact that program iterates through every line of code and gets 'length_of_list' which in case of choosing premade list will not be defined. My question is how can I completely jump over or avoid this if statement when I choose the 'premade list' option? I have tried to put it into while loop and break but doesn't work with my tries.
*I am not looking for ready answer. Please show me path to follow.
2 Answers 2
First of all, you should consider using elif. That way if your first condition is met, you do not need to check the second condition.
https://www.w3schools.com/python/python_conditions.asp
Second, I think somewhere later in the code, you are referencing length_of_list, which is only defined when you choose "own". When running, if question_choice == "premade" returns true, none of the code in "own" will run, and so it will not matter if length_of_list is defined or not.
Your problem is later on in the code, where you use the length_of_list variable. If you choose 'premade', you never define length_of_list.
Consider defining length_of_list in the question_choice == "premade" brach. Perhaps by using len(premade_list[quest]), assuming premade_list[quest] is a list, not a string!
If premade_list[quest] is a string, you'll have to use the .split() method befor using len().
if
branch is actually taken.) I suspect that something else is going on. Please edit your question to include all of the code and the full error message, which should tell you the exact line number of the problem.