PYTHON - Reverse Number Guessing Game - - python

So I've been trying to figure out a way to write a program where the computer tries to guess the number I am thinking of, instead of the other way around where you are guessing a computer's chosen number. It works most of the time however in some situations it does repeat numbers down the chain even though I've told it before that for example the value I am thinking of is higher than '7'. In some cases it also repeats the same number again even though I tell it its higher or lower. If someone more experienced could have a look at this and tell me what am I missing in these loops it would help a great deal.
#computer enters a value x
#lower - computer guesses lower than x
#higher - computer guesses higher than x
#when string "You got it!" - game over
import random
lowBound = 0
highBound = 100
randomNumber = random.randint(lowBound,highBound)
print ("Is it ", randomNumber, " ?")
response = input()
while response != "You got it!":
if response == "higher":
lowBound = randomNumber
randomNumber = random.randint (lowBound, highBound)
print ("Is it ", randomNumber, " ?")
response = input()
elif response == "lower":
highBound = randomNumber
randomNumber = random.randint (lowBound, highBound)
print ("Is it ", randomNumber, " ?")
response = input()
if response == "You got it!":
print ("Woohooo, I'm so bitchin'")

random.randint is inclusive, so:
if response == 'higher':
lowBound = randomNumber + 1
and
if response == 'lower':
highBound = randomNumber - 1
Also, if the user does not enter a valid response, input() will never be called again and the program will hang in an infinite loop.
Something more robust, but doesn't handle liars:
import random
lowBound = 0
highBound = 100
response = ''
randomNumber = random.randint(lowBound,highBound)
while response != "yes":
print ("Is it ", randomNumber, " ?")
response = input()
if response == "higher":
lowBound = randomNumber + 1
randomNumber = random.randint(lowBound,highBound)
elif response == "lower":
highBound = randomNumber - 1
randomNumber = random.randint(lowBound,highBound)
elif response == "yes":
print ("Woohooo, I'm so bitchin'")
break
else:
print ('Huh? "higher", "lower", or "yes" are valid responses.')

random.randint(a, b) returns a number between and including a and b. When generating a new random number you should use random.randint(lowBound+1, highBound-1)

One of your problems, among the others mentioned, is on these lines:
highBound = randomNumber
randomNumber = random.randint (lowBound, highBound)
You're setting a new bound, which is good, but then you're choosing another random number!
What you should be doing, is halving the bound, and asking the user higher or lower from there. Have a look at binary search algorithms.
highBound = randomNumber
randomNumber = randomNumber / 2
Your program is still going to work (with the other changes mentioned here), but this will guess your number quicker most of the time.
There is actually an example of this game on Wikipedia.

Here is my version of this exercise from Michael Dawson's book, I was trying to minimize number of tries, that computer uses. I know code looks dodgy, it is just my 2nd day:)
answer=""
guess=50
counter=3
x=25
print("hi, guess the number from 1 too 100")
input("\n")
print ("i will try to guess it")
print ("is it ", guess, "?")
while answer not in ("y","l","s"):
print ("sorry, i didn't understand \n")
answer=input("type in: (Y) for yes, or (L) if it is to large, or (S) if it is to small:")
if answer in ("s","l"):
while answer!="y":
if answer=="l":
guess=int(guess-x)
print ("how about", guess,"?")
answer=input("\nis it? type in: (Y) for yes, or (L) if it is to large, or (S) if it is to small:")
x=100/2**counter
counter=counter+1
if x<1:
x=1
elif answer=="s":
guess=int(guess+x)
print ("how about", guess,"?")
answer=input("\nis it? type in: (Y) for yes, or (L) if it is to large, or (S) if it is to small:")
x=100/2**counter
counter=counter+1
if x<1:
x=1
elif answer=="y":
break
else:
pass
print("\ngreat! the number that you guessed is", guess)
print("i can read your mind with no guesses!")
input("\n")

You get numbers twice because random.randint's boundaries are inclusive; random.randint(1, 3) can return 1,2, or 3. Note that you should also continue to ask the human if the response is neither "higher", nor "lower" nor "You got it!":
import random
lowBound = 0
highBound = 100
while True:
randomNumber = random.randint(lowBound, highBound)
print ("Is it ", randomNumber, " ?")
response = input()
if response == "higher":
lowBound = randomNumber + 1
elif response == "lower":
highBound = randomNumber - 1
if response == "You got it!":
print ("Woohooo, I'm so bitchin'")
break

Related

ValueError exception in python3?

I'm a python beginner and i was making a simple number guessing game, but every time i accidently type in a letter or a symbol instead of a number, i get the ValueError. How do I pass this error throughout the entire program? i know the code is messy, and I'm sorry for that but I'm just trying to have some fun with it.
import random
tries = 15
money = 0
cheat = 0
run = True
random_number = random.randint(1, 20)
while run:
if cheat >= 1:
print(random_number)
cheat -= 1
guess = input("Pick a number from 1-20! You have " + str(tries) + " tries")
guess = int(guess)
if guess == random_number:
money += 5
print("You got it right! You got it with " + str(tries) + " tries left", "your balance is", + money)
again = input("Play again? yes/no")
if again == "yes":
random_number = random.randint(1, 20)
else:
break
#store system
shop = input("Would you like to access the shop? yes/no")
if shop == "yes":
try_cost = 10
cheat_cost = 20
#if player has enough money
buy_try = input("Would you like to purchase more tries? price is 10 dollars for 5 tries. yes/no")
if buy_try == "yes" and money >= 10:
tries += 5
money -= 10
print("You have", tries, "tries", "and", money, "money", "and", cheat, "cheats")
buy_cheat = input("Would you like to purchase a cheat? price is 20 dollars for 2 cheats")
if buy_cheat == "yes" and money >= 20:
cheat += 2
money -= 20
print("You have", tries, "tries", "and", money, "money", "and", cheat, "cheats")
# if player doesn't have enough money
elif buy_try == "yes" and money != 10:
print("You don't have enough for that, you have", money, "dollars")
elif buy_cheat == "yes" and money != 20:
print("You don't have enough for that, you have", money, "dollars")
elif guess > random_number:
print("Try a little lower!")
tries -= 1
elif guess < random_number:
print("Try a little higher!")
tries -= 1
if tries == 0:
print("you ran out of tries!")
run = False
Pick a number from 1-20! You have 15 triess
Traceback (most recent call last):
File "C:\Users\bashr\PycharmProjects\pythonProject1\main.py", line 15, in
guess = int(guess)
ValueError: invalid literal for int() with base 10: 's'
In this situation, use a try and except clause.
Documentation: https://docs.python.org/3/tutorial/errors.html#handling-exceptions
assuming you want to access that error inside this whole file then you can use global variable or you can use class concept
I think the fastest way to solve that is a while: while the input Is not a digit ask again the input.
So, in your case, every time you use the input function you should use something likes this:
guess = input("Pick a number from 1-20! You have " + str(tries) + " tries")
while not guess.isdigit():
print("the input Is not a digit, please retry")
guess = input("Pick a number from 1-20! You have...")
Or you can use you can use try and except

Computer guessing number python

I'm very new to programming and am starting off with python. I was tasked to create a random number guessing game. The idea is to have the computer guesses the user's input number. Though I'm having a bit of trouble getting the program to recognize that it has found the number. Here's my code and if you can help that'd be great! The program right now is only printing random numbers and won't stop even if the right number is printed that is the problem
import random
tries = 1
guessNum = random.randint(1, 100)
realNum = int(input("Input a number from 1 to 100 for the computer to guess: "))
print("Is the number " + str(guessNum) + "?")
answer = input("Type yes, or no: ")
answerLower = answer.lower()
if answerLower == 'yes':
if guessNum == realNum:
print("Seems like I got it in " + str(tries) + " try!")
else:
print("Wait I got it wrong though, I guessed " + str(guessNum) + " and your number was " + str(realNum) + ", so that means I'm acutally wrong." )
else:
print("Is the number higher or lower than " + str(guessNum))
lowOr = input("Type in lower or higher: ")
lowOrlower = lowOr.lower()
import random
guessNum2 = random.randint(guessNum, 100)
import random
guessNum3 = random.randint(1, guessNum)
while realNum != guessNum2 or guessNum3:
if lowOr == 'higher':
tries += 1
import random
guessNum2 = random.randint(guessNum, 100)
print(str(guessNum2))
input()
else:
tries += 1
import random
guessNum3 = random.randint(1, guessNum)
print(str(guessNum3))
input()
print("I got it!")
input()
How about something along the lines of:
import random
realnum = int(input('PICK PROMPT\n'))
narrowguess = random.randint(1,100)
if narrowguess == realnum:
print('CORRECT')
exit(1)
print(narrowguess)
highorlow = input('Higher or Lower Prompt\n')
if highorlow == 'higher':
while True:
try:
guess = random.randint(narrowguess,100)
print(guess)
while realnum != guess:
guess = random.randint(narrowguess,100)
print(guess)
input()
print(guess)
print('Got It!')
break
except:
raise
elif highorlow == 'lower':
while True:
try:
guess = random.randint(1,narrowguess)
print(guess)
while realnum != guess:
guess = random.randint(1,narrowguess)
print(guess)
input()
print(guess)
print('Got It!')
break
except:
raise
This code is just a skeleton, add all of your details to it however you like.

Dice Game score and beginning doesn't work

I recently started learning python and am trying to make a simple game in python 2.7 where a computer randomly generates a number between 1 and 6 while the player enters a number between 1 and 6. The rule is that the bigger number wins except if one person has 6 and the other has 1 in which case the person with the 1 wins. The game should also ask a first question and if the player answers "yes" then the game would continue. Else it would do other processes. When I run the code however, even if the number the computer generated is higher, it doesn't add any points to the computer. Also if I enter no or something else, the code proceeds to start the game even though I am trying to get the code to print some other lines.
I have tried just using if else statements without try and except as well as changing the beginning prompt to be a boolean statement.
import random as r
score1 = 0
score2 = 0
start = raw_input("Would you like to start a new game")
if start == "yes" or " yes":
print "Choose a number between 1 and 6"
print "Enter stop to end game"
choice1 = raw_input("Pick a number")
choice2 = r.randint (1,6)
while choice1 != "stop":
try:
if choice1 > choice2:
score1 = score1 + 1
print "The computer picked: " + str(choice2)
choice1 = raw_input("Pick a number")
choice2 = r.randint(1, 6)
elif choice2 > choice1:
score2 = score2 + 1
print "The computer picked: " + str(choice2)
choice1 = raw_input("Pick a number")
choice2 = r.randint(1, 6)
except:
if choice1 == 1 and choice2 == 6:
score1 = score1 + 1
print "The computer picked: " + str(choice2)
choice1 = raw_input("Pick a number")
choice2 = r.randint(1, 6)
else:
if choice1 == 6 and choice2 == 1:
score2 = score2 + 1
print "The computer picked: " + str(choice2)
choice1 = raw_input("Pick a number")
choice2 = r.randint(1, 6)
print "Final score is: " + str(score1) + " and Computer is: " + str(score2)
elif start == "no" or " no":
print "Maybe another time"
else:
print "Please enter yes or no"
start = raw_input("Would you like to start a new game")
Program output:
Would you like to start a new game no
Choose a number between 1 and 6
Enter stop to end game
Pick a number1
The computer picked: 2
Pick a number1
The computer picked: 4
Pick a number1
The computer picked: 5
Pick a number1
The computer picked: 3
Pick a numbersotp
The computer picked: 2
Pick a numberstop
Final score is: 5 and Computer is: 0
Process finished with exit code 0
Firstly, this statement
if start == "yes" or " yes":
Is evaluated as (start == 'yes') or ('yes'). Since ' yes' is a constant and always true, it will always evaluate as true. Instead try this, it will take spaces off the front or back before evaluating.
if start.strip() == 'yes':
I would also look at the other places where you if then with multiple conditions. Consider using parens to ensure the code is evaluating as you expect. For instance,
if (choice1 == 1) and (choice2 == 6):
Also, try\expect is intended for exception logging. I'm not sure what exceptions you expect to log here. Probably better to check the user input and make sure it's a number explicitly rather than relying on try\expect

Program not exiting after multiple games?

from random import random
# This function handles the number guessing and number formatting
def run_game():
# rand is declared by grabbing a number between 0 and 1, multiplying it by 100, and rounds to nearest integer
rand = round(random() * 100, 0)
print("Guess the number [0 - 100]")
guesses = 0
while True:
# Assigns the 'answer' variable by grabbing user input from console
answer = input()
# Checks if the input from the console is a number, and if not, asks the user to enter a valid number
if answer.isdigit():
n = int(answer)
if n > int(rand):
print("Number is less than " + str(n))
guesses = guesses + 1
elif n < int(rand):
print("Number is greater than " + str(n))
guesses = guesses + 1
else:
guesses = guesses + 1
print("It took you " + str(guesses) + " guesses to guess the right number!")
reply = play_again()
if reply is False:
break
else:
run_game()
else:
print("Please enter a number")
def play_again():
while True:
reply = input("Play again? (y/n)\n")
if reply.lower() == "y":
return True
elif reply.lower() == "n":
return False
else:
print("Enter 'y' or 'n'")
if __name__ == "__main__":
run_game()
So when I run this program, it runs fine. Once guessing the number, I can type y or n to play again. If I have only played once, it works fine. But if I select y, and play again, entering n after playing the second game does nothing
Your main issue is that you're using recursion to start a new game, but after the recursive call returns (assuming it does), you just keep on going in the original game.
There are a few ways you could fix that. The simplest would be to change the code that handles checking the user's choice to play again so that it always breaks:
if reply:
run_game()
break
A better approach would be to get rid of the recursion. There are a few ways you could do that. One simple idea is to simply reset the appropriate variables and keep right on going with your game loop when the user wants to play again:
reply = play_again()
if reply:
rand = round(random() * 100, 0)
print("Guess the number [0 - 100]")
guesses = 0
else:
break
Another way to avoid recursion would be to add another loop. Here's one way you could do it with a separate function:
def run_game():
rand = round(random() * 100, 0)
print("Guess the number [0 - 100]")
guesses = 0
while True:
answer = input()
if answer.isdigit():
n = int(answer)
if n > int(rand):
print("Number is less than " + str(n))
guesses = guesses + 1
elif n < int(rand):
print("Number is greater than " + str(n))
guesses = guesses + 1
else:
guesses = guesses + 1
print("It took you " + str(guesses) + " guesses to guess the right number!")
break # unconditionally break here!
def run_many_games():
again = True
while again:
run_game()
again = play_again()
One thing you may note that I've changed in all of the code above is how I test if the return value from play_again is True or False. There's no need for an extra comparison step when you have a bool value already. Just do if reply (or if not reply if you're testing for False). You can also do this in a while loop condition, as I do with again in my last code block.
Heres a good way to solve this problem. In your code you never actually exit the while loop because run game never exits, and there is no system variable returned to break it. Using sys.exit(0) also works, but its a bad habit to get into for these kinds of programs.
from random import random
# This function handles the number guessing and number formatting
def run_game():
# rand is declared by grabbing a number between 0 and 1, multiplying it by 100, and rounds to nearest integer
rand = round(random() * 100, 0)
print("Guess the number [0 - 100]")
guesses = 0
while True:
answer = input()
if type(answer) == int:
n = int(answer)
if n > int(rand):
print("Number is less than " + str(n))
guesses = guesses + 1
elif n < int(rand):
print("Number is greater than " + str(n))
guesses = guesses + 1
else:
guesses = guesses + 1
print("It took you " + str(guesses) + " guesses to guess the right number!")
break
reply = play_again()
if reply:
run_game()
else:
print 'Thank you for playing'
def play_again():
while True:
reply = raw_input("Play again? (y/n)\n")
if reply.lower() == "y":
return True
elif reply.lower() == "n":
return False
else:
print("Enter 'y' or 'n'")
if __name__ == "__main__":
run_game()
The reason this is happening is because run_game ends up calling itself recursively. Instead of restarting the game when the user chooses to play again it effectively creates a new instance of the game. Then when the user chooses to stop playing it returns back to the old session instead of exiting the program.
You can even prove this to yourself by remembering the solution before choosing to play again, and then choosing not to play again after the second session. You'll then be playing the previous session again and entering the solution you remembered or wrote down.
Now you can solve this problem by using sys.exit() instead of break to force the program to close, but that doesn't seem like good practice. If somebody chooses to play again too many times they can cause the program to run out of stack space and crash. Instead it's probably better to move that check out of run_game like this
if __name__ == "__main__":
while True:
run_game()
if not play_again():
break
And modify the else block in run_game to this
else:
guesses = guesses + 1
print("It took you " + str(guesses) + " guesses to guess the right number!")
break
There's no point in returning True or False according to the user input, you can work from there directly.
import sys
from random import random
# This function handles the number guessing and number formatting
def run_game():
# rand is declared by grabbing a number between 0 and 1, multiplying it by 100, and rounds to nearest integer
rand = round(random() * 100, 0)
print("Guess the number [0 - 100]")
guesses = 0
while True:
# Assigns the 'answer' variable by grabbing user input from console
answer = input()
# Checks if the input from the console is a number, and if not, asks the user to enter a valid number
if answer.isdigit():
n = int(answer)
if n > int(rand):
print("Number is less than " + str(n))
guesses = guesses + 1
elif n < int(rand):
print("Number is greater than " + str(n))
guesses = guesses + 1
else:
guesses = guesses + 1
print("It took you " + str(guesses) + " guesses to guess the right number!")
play_again()
else:
print("Please enter a number")
def play_again():
while True:
reply = input("Play again? (y/n)\n")
if reply.lower() == "y":
run_game()
elif reply.lower() == "n":
sys.exit(0)
else:
print("Enter 'y' or 'n'")
if __name__ == "__main__":
run_game()
This way the code is somewhat cleaner and fixes your problem. There's no point in passing "flags" around when you can do things directly.
Since your game is from 0 to 100 you should also verify if the user doesn't put a number that's bigger than 100, since lower than 0 doesn't pass the isdigit check.

How do i fix the error in my hangman game in Python 3

This code is from a small game i've been working on over the past day or so, i know i shouldn't really post the whole code but i'm not entirely sure which part of the code is not working as intended, any help would be appreciated. the code is a hangman game and i am aware of the huge amount of repetition in the code but am unsure how to reduce it to one of every function that will work with each difficulty setting.
import random
import time
#Variables holding different words for each difficulty
def build_word_list(word_file):
words = [item.strip("\n") for item in word_file]
return words
EASYWORDS = open("Easy.txt","r+")
MEDWORDS = open("Med.txt","r+")
HARDWORDS = open("Hard.txt","r+")
INSANEWORDS = open("Insane.txt", "r+")
easy_words = build_word_list(EASYWORDS)
medium_words = build_word_list(MEDWORDS)
hard_words = build_word_list(HARDWORDS)
insane_words = build_word_list(INSANEWORDS)
#Where the user picks a difficulty
def difficulty():
print("easy\n")
print("medium\n")
print("hard\n")
print("insane\n")
menu=input("Welcome to Hangman, type in what difficulty you would like... ").lower()
if menu in ["easy", "e"]:
easy()
if menu in ["medium", "med", "m"]:
med()
if menu in ["hard", "h"]:
hard()
if menu in ["insane", "i"]:
insane()
else:
print("Please type in either hard, medium, easy or insane!")
difficulty()
def difficulty2():
print("Easy\n")
print("Medium\n")
print("Hard\n")
print("Insane\n")
print("Quit\n")
menu=input("Welcome to Hangman, type in the difficulty you would like. Or would you like to quit the game?").lower()
if menu == "hard" or menu == "h":
hard()
elif menu == "medium" or menu == "m" or menu =="med":
med()
elif menu == "easy" or menu == "e":
easy()
elif menu == "insane" or menu == "i":
insane()
elif menu == "quit" or "q":
quit()
else:
print("Please type in either hard, medium, easy or insane!")
difficulty()
#if the user picked easy for their difficulty
def easy():
global score
print ("\nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10:
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
print ("the word was, ", word)
difficultyEASY()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyEASY()
#if the user picked medium for their difficulty
def med():
global score
print ("\nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10:
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
difficultyMED()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyMED()
#if the user picked hard for their difficulty
def hard():
global score
print ("\nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10: #try to fix this
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
difficultyHARD()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyHARD()
#if the user picked insane for their difficulty
def insane():
global score
print ("This words may contain an apostrophe. \nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10: #try to fix this
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
difficultyINSANE()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyINSANE()
def start():
Continue = input("Do you want to play hangman?").lower()
while Continue in ["y", "ye", "yes", "yeah"]:
name = input("What is your name? ")
print ("Hello, %s, Time to play hangman! You have ten guesses to win!" % name)
print ("\n")
time.sleep(1)
difficulty()
else:
quit
#whether they want to try a diffirent difficulty or stay on easy
def difficultyEASY():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
easy()
#whether they want to try a diffirent difficulty or stay on medium
def difficultyMED():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
med()
#whether they want to try a diffirent difficulty or stay on hard
def difficultyHARD():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
hard()
#whether they want to try a diffirent difficulty or stay on insane
def difficultyINSANE():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
insane()
score = 0
start()
When i run this code the error i get is:
Traceback (most recent call last):
File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 316, in <module>
start()
File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 274, in start
difficulty()
File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 41, in difficulty
insane()
File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 227, in insane
word = random.choice(words).lower()
NameError: name 'words' is not defined
I'm not sure what is wrong with words or how to fix it.
Your words variable is only defined in the scope of build_word_list function.
All the other functions don't recognize it so you can't use it there.
You can have a "quickfix" by defining it as a global variable, although usually using global variables isn't the best practice and you might want to consider some other solution like passing words to your other functions that use it or use it within the confines of a class.
(If avoiding global variables interests you, maybe you would like to read this and this)
You have words defined in the method build_word_list.
You should declare words as a global variable so that it can be accessed everywhere or restructure you program into a class and use self to reference it.

Categories