Invalid Syntax. No area highlighted [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
In here somewhere. P.S. Its a cricket game. Nowhere in the code is highlighted. What can I do? Thanks in advance for answering. I need this for an assignment. It worked fin untill I edited the area where it displays the runs scored by the player. I was going to add how many wickets had fallen, but somwhere in this time frame I messed up. Thanks
playruns = playtemp
playscore = playscore + playruns
print("You scored" ,playruns, "runs.", team, "is on", playscore," runs.")
elif playruns == 5:
print("Your player is out! ", team,"'s current score is:", playscore,"runs")
playouts = playouts + 1
if playouts == 5:
print("You are all out. Now it is your turn to bowl.")
while compouts != 5:
print("The Androidz scored", compruns,"runs. The total score of the Androidz is", compscore,"runs.")
compruns = 0
comptemp = 0
compouts = compouts + 1
if compouts == 5:
print("Game over man, game over.")
print("Your score was:", playscore,)
print("The Androidz score was:", compscore.)
if playscore > compscore:
playagain = input("You are the winner.
print("The Androidz scored", compruns,"runs. The total score of the Androidz is", compscore.)
compruns = 0
comptemp = 0
compouts = compouts + 1
if compouts == 5:
print("The Androidz are all out. Congratulations.")
while playouts != 5:
print("You are now batting.")
playmindset = input("For this ball would you like to play agressively 'a', or defensively 'd'")
if playmindset == "a":
playtemp = random.choice([1,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,])
elif playmindset == "d":
playtemp = random.choice([1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,4,4,4,5,5,5,])
playruns = playtemp
playscore = playscore + playruns
if playruns != 5:
print("You scored" ,playruns, "runs.", team, "is on", playscore,"runs")
elif playruns == 5:
print("Your player is out! ", team,"'s current score is:", playscore.)
playouts = playouts + 1
if playouts == 5:
print("Game over man, game over.")
print("Your score was:", playscore,)
print("The Androidz score was:", compscore,)
if playscore > compscore:
playagain = input("You are the winner. Play againg?. 'y' for yes, 'n' for no.")
elif playscore < compscore:
playagain = input("You are the loser. Play againg?. 'y' for yes, 'n' for no.")
elif coinguess != headsortails:
while compouts != 5:
print("You lost the toss. You are bowling.")
print("The Androidz are at the crease. The hot sun beams down upon the ground.\nVictory is a must for", team, "if" , captainname, "wishes to remain as captain.")
bowltodo = input("Would you like to bowl or forfeit?")
comptemp = random.choice([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,])
if bowltodo == "bowl":
compruns = comptemp
compscore = compruns + compscore
print("The Androidz scored", compruns,"runs. The total score of the Androidz is",compscore,"runs.")
compruns = 0
comptemp = 0
compouts = compouts + 1
if compouts == 5:
print("The Androidz are all out. Congratulations.")
while playouts != 5:
print("You are now batting.")
playmindset = input("For this ball would you like to play agressively 'a', or defensively 'd'")
if playmindset == "a":
playtemp = random.choice([1,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,6,6,6,6,6,6,6,6,6,])
elif playmindset == "d":
playtemp = random.choice([1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,5,5,])
playruns = playtemp
playscore = playscore + playruns
if playruns != 5:
print("You scored" ,playruns, "runs.", team, "is on", playscore.)
elif playruns == 5:
print("Your player is out! ", team,"'s current score is:", playscore.)
playouts = playouts + 1
if playouts == 5:
print("Game over man, game over.")
print("Your score was:", playscore,)
print("The Androidz score was:",compscore,)
if playscore > compscore:
playagain = input("You are the winner. Play againg?. 'y' for yes, 'n' for no.")
elif playscore < compscore:
playagain = input("You are the loser. Play againg?. 'y' for yes, 'n' for no.")

You have several syntax errors. The first one is here on line 33
elif playmindset == "d":
playtemp = random.choice([1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,5,5,])
playruns = playtemp
playscore = playscore + playruns
print("You scored" ,playruns, "runs.", team, "is on", playscore," runs.")
elif playruns == 5: # this line
print("Your player is out! ", team,"'s current score is:", playscore,"runs")
playouts = playouts + 1
That second elif raises a syntax error because there is no if that precedes it. Perhaps you meant to place the 3 lines in between the 2 elifs in the first one, or maybe make the second elif a new if. That is for you to fix.
Furhermore syntax errors are raised because you print stuff like this at several places in your program (lines 52, 66, 84, 120, 122)
print("The Androidz score was:", compscore.)
the . behind compscore insinuates you are going to call a function on it, or a property or something. Because you do not do that it raises a syntax error. I think you just want to print a dot at the end of the line, in that case just change them to
print("The Androidz score was:", compscore + ".")

Related

Boolean does not control while loop for me

All of this code does not get affected by a SIGKILL command and my while loop continues no matter what condition
Code:
if Play == False:
signal.SIGKILL(0)
if gameplayint == "N":
print("What are you doing here then?")
Play == False
if gameplayint == "Y":
Play == True
time.sleep(0.5)
print("We will start now.")
#Start the game.
print("")
#Actual gameplay block of code
#game start
while Play == True:
pcNum = random.randint(1,19)
anotherNum = True
total = 0
while anotherNum == True:
playerNum = random.randint(1,10)
total = total + playerNum
print("")
print("Your number is ", str(playerNum) + ".")
print("You have " + str(total) + " in total.")
print("")
again = input("Roll another number? <Y or N> ")
print("")
if again == "Y":
anotherNum = True
else:
anotherNum = False
break
#game finished now
print("Computer got", pcNum)
print("You got", total)
#checking for winner
while anotherNum == False:
if (total <= 13) and (total > pcNum):
print("You,", name, "have won!")
elif (pcNum <= 13) and (pcNum > total):
print("The computer has bested you,", name + "!")
else:
if (total == pcNum) and (total <= 13):
print("Draw...")
elif (pcNum > 13) and (total <= 13):
print("You,", name + " have won!")
else:
print("Both of you have lost. Wow...")
again = input("Try again? <Y or N>")
if again == "Y":
Play = True
else:
Play = False
print("Goodbye now.")
Output:
What's your name? Y
Very well then Y, do you want to play 13? <Y or N> N
What are you doing here then?
Your number is 3.
You have 3 in total.
The issue here is that despite N being outputted on the gameplayint variable, the while loop still continues instead of stopping the output entirely.

establishing a win streak in dice game

Hi all. Really, REALLY stuck here. I've updated my code below.
I'm trying to establish a counter to track games played, correct guesses and > incorrect guesses plus, when the number of consecutive correct guesses
= 4 or user stops playing, game summary is provided.
I cannot get the counter to work correctly.
Help appreciated!
import math
import dice
import random
# Print introduction and game explanation
print ("")
print ("")
print ("Would you like to play a game?")
print ("The game is...'Petals Around the Rose'. Cool eh?")
print ("Pay attention - the name of the game is important.")
print ("Each round, five dice are rolled and")
print ("You'll be asked for the score. (Hint? The score")
print ("will always be either 'zero' or an even number).")
print ("Your challenge is to deduce how the computer has")
print ("calculated the score.")
print ("You need to input your guess, after which")
print ("You'll learn if you were right. If not, you'll")
print ("be told the correct score & asked to roll again.")
print ("If you can guess correctly four times in a row,")
print ("You'll be declared the winner and receive the")
print ("majestic title of 'Potentate of the Rose'")
print ("")
# Define win count (four correct guesses in a row required)
win_count = 0
# Obtain input from user:
answer = input("Are you up for the challenge? Enter 'y' or 'n' : ")
# If answer = no, exit game
if answer == 'n':
print("Really? fine then. See ya!")
exit()
# If answer = yes, commence game
elif answer == 'y':
print("")
print ("Ok...here comes the first roll!")
print("")
# import dice representation
import dice
# Roll random dice x 5
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
die3 = random.randint(1, 6)
die4 = random.randint(1, 6)
die5 = random.randint(1, 6)
dice.display_dice(die1, die2, die3, die4, die5)
# Obtain player's guess for the roll
roll_guess = int(input("Enter your guess for this roll: "))
# Define die results for all dice for guess purposes to
# match the 'petals around the rose'. So, if roll a 2, 4 or 6,
# the result is zero. If return a 3, the result is 2. If
# return a 5, the result is 4.
def roll_result(die1):
if die1 == 1 or die1 == 2 or die1 == 4 or die1 == 6:
die1 = 0
elif die1 == 3:
die1 = 2
elif die1 == 5:
die1 = 4
return die1
def roll_result(die2):
if die2 == 1 or die2 == 2 or die2 == 4 or die2 == 6:
die2 = 0
elif die2 == 3:
die2 = 2
elif die2 == 5:
die2 = 4
return die2
def roll_result(die3):
if die3 == 1 or die3 == 2 or die3 == 4 or die3 == 6:
die3 = 0
elif die3 == 3:
die3 = 2
elif die3 == 5:
die3 = 4
return die3
def roll_result(die4):
if die4 == 1 or die4 == 2 or die4 == 4 or die4 == 6:
die4 = 0
elif die4 == 3:
die4 = 2
elif die4 == 5:
die4 = 4
return die4
def roll_result(die5):
if die5 == 1 or die5 == 2 or die5 == 4 or die5 == 6:
die5 = 0
elif die5 == 3:
die5= 2
elif die5 == 5:
die5 = 4
return die5
# tally all 5 dice rolls
a = roll_result(die1)
b = roll_result(die2)
c = roll_result(die3)
d = roll_result(die4)
e = roll_result(die5)
total_roll_result = a + b + c + d + e
# Compare user input to dice result
if roll_guess == total_roll_result:
print("")
print('Well done! You guessed it!')
print("")
elif guess % 2 == 0:
print("")
print("No sorry, it's", total_roll_result, "not", roll_guess)
print("")
else:
print("")
print ("No, sorry, it's", total_roll_result, 'not', roll_guess,"")
print ("Remember,the answer will always be an even number")
print("")
# Obtain user input if continuing to play
another_attempt = input("Are you up to play again? If so, enter y or n ")
print("")
# Commence loop and win count.
while another_attempt == 'y' and win_count <4:
# Commence win count
win_count = 0
# Commence games played count
games_played = 0
# Commence incorrect guesses count
incorrect_guesses = 0
# If user has not yet gotten 4 guesses in a row:
if win_count < 4:
die1 = random.randint(1,6)
die2 = random.randint(1,6)
die3 = random.randint(1,6)
die4 = random.randint(1,6)
die5 = random.randint(1,6)
result = dice.display_dice(die1, die2, die3, die4, die5)
a = roll_result(die1)
b = roll_result(die2)
c = roll_result(die3)
d = roll_result(die4)
e = roll_result(die5)
total_roll_result = a + b + c + d + e
roll_guess = int(input('Enter your guess for this roll: '))
print("")
if roll_guess == total_roll_result:
# Update win count
win_count += 1
# Update games played count
games_played += 1
print("")
print('Nice work - you got it right!')
elif roll_guess %2 == 0:
# reset win count
win_count = 0
# Update games played count
games_played += 1
# Update incorrect guesses count
incorrect_guesses += 1
print("")
print("Nah, sorry, it's", total_roll_result, "not", roll_guess)
else:
# Reset win count
win_count = 0
# Update games played count
games_played += 1
# Update incorrect guesses count
incorrect_guesses += 1
print("")
print ("Nah, sorry, it's", total_roll_result, 'not', roll_guess,"")
print ("Remember,the answer will always be an even number")
print("")
another_attempt = input("Are you up to play again? ")
# Quit loop if user no longer wishes to play
# Provide game summary
if another_attempt == 'n':
print ("")
print ("Game Summary")
print ("------------")
print ("")
print ("You played ", games_played, "games.")
print ("")
print ("You had ", correct_guesses, "overall and ")
print ("")
print ("a total of ", incorrect_guesses, "overall ")
print ("")
print ("Cheerio!")
exit()
if win_count == 4:
# Inform player has correctly guessed 4 in a row
# Print congratulations message
print ("")
print ("")
print ("You've done it! You've successfully guessed")
print ("Four times in a row. Looks like you worked ")
print ("out the secret. Now, stay stum & tell no one!")
print ("")
# Provide game summary
print ("Game Summary")
print ("")
# Provide tally of games played & print:
print ("You played ", games_played, "games.")
print ("")
# Provide tally of correct guesses & print:
print ("You had ", correct_guesses, "overall and ")
print ("")
# Provide tally of total incorrect guesses & print:
print ("a total of ", incorrect_guesses, "overall ")
print ("")
print ("Cheerio!")
exit()
def game_stats():
win_count
games_played
incorrect_guesses
You look very lost here. This part does not make any sense
def win_count():
win_count() == 0
correct == total_roll_result
I think you mean something like this
win_count = 0
correct = total_roll_result == roll_guess
Note
When you say
def win_count:
# some code
you are defining win_count as a function! But clearly you want win_count to be an integer counting something.

Python Random Number Guessing Game (cant get the average guess right)

I'm newly introduced to Python but I am now currently stuck with this code of mine where I just can't get the average guess game per game to work. If I could receive some help from you guys that'll be great! I would also love to hear any constructive feedback if there's any. Thank you!!
# A robust number-guessing game with hinting.
import random
total_guess = 0
num_games = 0
num_guesses = 0
print("Welcome to Guessing Game!")
print()
reply = input("Are you ready to play (Y or N)?").upper()
while reply != "Y" and reply != "N":
print("Invalid response")
reply = input("Another game (Y or N)? ").upper()
while reply == "Y":
# pick a random number from 0 to 100 (both inclusive)
# There is no error in the line below, which is
# equivalent to
# number = random.randint(0, 100)
number = random.randrange(0, 101)
# make it different from number so that it goes into loop
guess = number + 1
while guess != number :
guess = int(input("Your guess (0 - 100)? "))
num_guesses += 1
if guess < number :
print("Your guess is too low")
elif guess > number :
print("Your guess is too high")
else:
print("Bingo!")
# collect the statistics to calculate average guess per game
total_guess += num_guesses
num_games += 1
print("You got it right in " + str(num_guesses) + " tries.")
num_guesses = 0
print()
reply = input("Another game (Y or N)? ").upper()
while reply != "Y" and reply != "N":
print("Invalid response")
reply = input("Another game (Y or N)? ").upper()
print("Your average guess per game is", total_guess/num_games)
Your code was not properly indented.
import random
total_guess = 0
num_games = 0
num_guesses = 0
print("Welcome to Guessing Game!")
print()
reply = input("Are you ready to play (Y or N)?").upper()
while reply != "Y" and reply != "N":
print("Invalid response")
reply = input("Another game (Y or N)? ").upper()
while reply == "Y":
number = random.randrange(0, 11)
# make it different from number so that it goes into loop
guess = number + 1
while guess != number :
guess = int(input("Your guess (0 - 100)? "))
num_guesses += 1
if guess < number :
print("Your guess is too low")
elif guess > number :
print("Your guess is too high")
else:
print("Bingo!")
# collect the statistics to calculate average guess per game
total_guess += num_guesses
num_games += 1
print("You got it right in " + str(num_guesses) + " tries.")
num_guesses = 0
print()
reply = input("Another game (Y or N)? ").upper()
while reply != "Y" and reply != "N":
print("Invalid response")
reply = input("Another game (Y or N)? ").upper()
print("Your average guess per game is", total_guess/num_games)

how can i reset te score variable after every loop so they dont add up?

so i have run this code 3 times as there is 3 loops, however after every loop, the score variable seems to add itself on from the previous loop for e.g 1st loop (first user) gets a score of 2, then 2nd user get 4 and the last user gets 6. when i want to individually output all 3 users scores seperately, the code just adds on the scores. therefore this results in false scores. any solution to fix the score variable to reset every loop but still be attached to the 'schooldata[x]['score']' (x being the user number for e.g user 2 score would be 'schooldata[1]['score']) and which this outputs 3 seperate scores, specific to each user.
score = 0
schooldata = []
for x in range (0,3):
quiz = dict()
print ("Enter your name")
quiz['name'] = input()
print ("what class")
quiz['class_code'] = input()
print("1. 9+10=")
answer = input()
answer = int(answer)
if answer == 19:
print("correct")
score = score + 1
else:
print("wrong")
print("2. 16+40=")
answer = input()
answer = int(answer)
if answer == 56:
print("correct")
score = score + 1
else:
print("wrong")
print("3. 5+21=")
answer = input()
answer = int(answer)
if answer == 26:
print("correct")
score = score + 1
else:
print("wrong")
print("4. 5-6=")
answer = input()
answer = int(answer)
if answer == -1:
print("correct")
score = score + 1
else:
print("wrong")
print("5. 21-9=")
answer = input()
answer = int(answer)
if answer == 12:
print("correct")
score = score + 1
else:
print("wrong")
print("6. 12-11=")
answer = input()
answer = int(answer)
if answer == 1:
print("correct")
score = score + 1
else:
print("wrong")
print("7. 5*6=")
answer = input()
answer = int(answer)
if answer == 30:
print("correct")
score = score + 1
else:
print("wrong")
print("8. 1*8=")
answer = input()
answer = int(answer)
if answer == 8:
print("correct")
score = score + 1
else:
print("wrong")
print("9. 4*6=")
answer = input()
answer = int(answer)
if answer == 24:
print("correct")
score = score + 1
else:
print("wrong")
print("10. 9*10=")
answer = input()
answer = int(answer)
if answer == 90:
print("correct")
score = score + 1
else:
print("wrong")
quiz['score'] = score
schooldata.append(quiz)
user1=("name - ", schooldata[0]['name'],", user score - ", schooldata[0]['score'],", class number - ", schooldata[0]['class_code'])
print ("if you want student 1's results and information, please type 'user[0][0]'")
user = input()
if user == "user1":
print ("name - ", schooldata[0]['name'],", user score - ", schooldata[0]['score'],", class number - ", schooldata[0]['class_code'])

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