this is my hangman program. it returns a "NameError: name 'a' is not defined." please help me in fixing this. thank you very much.
import random
invalid= [" ","'",".",",","'", '"', "/", "\ ", '"',";","[","]", "=", "-", "~", "`", "§","±","!","#","#","$","%","^","&","*","(",")","_","+","{","}","|",":","?",">","<","0","1","2","3","4","5","6","7","8","9"]
choice = 0
print("Welcome to HANGMAN!")
def Menu():
print("[1] Play Hangman")
print("[2] Instructions ")
print("[3] Highscores")
print("[4] Exit")
choice = int(input("Please choose from the Menu: "))
if(not(choice <=4)):
print("Choose again.")
return Menu()
return choice
while True:
choice = Menu()
if choice == 1:
print("Categories: ")
print("[1] Movies")
print("[2] Animals")
print("[3] Something Blue")
choice_category = int(input("Please Choose a Category: "))
print("-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-")
print("Difficulties:")
print("[1] Easy")
print("[2] Average")
print("[3] Difficult")
choice_difficulty = int(input("Please Choose a Difficulty: "))
superword = a(choice_category, choice_difficulty)
legitgame(superword)
elif choice == 2:
print("Let yourself be hanged by mistaking the letters.")
elif choice == 3:
readHandle = open("Scores.txt","r")
names = []
for line in readHandle:
name = line[:-1]
names.append(name)
readHandle.close()
print()
Menu()
elif choice == 4:
print("Thank you for playing.")
Menu()
hangman =[" =========="
" | |"
" O |"
" |"
" |"
" | ",
" =========="
" | |"
" O |"
" | |"
" |"
" | ",
" ========== "
" | |"
" O |"
" /| |"
" |"
" | ",
" =========="
" | |"
" O |"
" /|\ |"
" |"
" | ",
" =========="
" | |"
" O |"
" /|\ |"
" / |"
" | ",
" =========="
" | |"
" O |"
" /|\ |"
" / \ |"
" | "]
#definition function for different options in a specific category and difficulty
def a(choice_category, choice_difficulties):
if choice_category == 1:
readHandle = open("movies.txt", 'r')
lines = readHandle.readlines()
elif choice_category == 2:
readHandle = open("animals.txt", 'r')
lines = readHandle.readlines()
elif choice_category == 3:
readHandle = open("something blue.txt", 'r')
lines = readHandle.readlines()
else:
print("Please choose again.")
if choice_difficulty == 1:
word = (lines[0])
elif choice_difficulty == 2:
word = (lines[1])
elif choice_difficulty == 3:
word = (lines[2])
else:
print("Please enter valid characters.")
legitword = word[:-1].split(".")
return (random.choice(legitword))
def legitgame (meh):
length = "__" * len(meh)
characters = []
mistake = 0
while mistake < 6 and length != meh:
print(hangman[mistake])
print(length)
print("Number of wrong guesses: ", mistake)
guess = (input("Guess:")).upper()
while len(guess) != 1:
print("You have inputted multiple letters. Please input a single letter.")
guess = input("Guess: ").upper()
while guess in invalid:
print("You have inputted an invalid character. Please try again.")
guess = input ("Guess: ").upper()
while guess in characters:
print("You have already inputted this letter. Please try again.")
guess= input("Guess: ").upper()
if guess in meh:
print()
print("Fantastic! You have entered a correct letter.")
characters.append(guess)
correct = ""
for x in range (0,len(meh)):
if guess == meh[x]:
correct += guess
else:
correct += length[x]
length = correct
else:
character.append(guess)
print("Sorry. You have inputted an incorrect letter. Please try again.")
mistake += 1
if mistake >= 6:
print(hangman[6])
print("The correct word is: ", meh)
print("Sorry. You killed the guy. Your conscience is chasing you.")
print("Game over")
elif correct == meh:
print("Congratulations! You saved the puny man.")
print("You have guessed ", word, "correctly!")
win()
Menu()
def win():
readHandle = open("Scores.txt", "a")
name = input("Enter your name: ")
readHandle.write(name + "\n")
readHandle.close
menu()
I can't tell for sure with the entire code, but from the given code I assume the error is that you call a(choice_category, choice_difficulty) before you have defined it. Put the def a(... before superword = a(choice_category, choice_difficulty), and you should be good to go (if this is indeed the problem)
"a" is apparently a function in your program as you have :
def a(choice_category, choice_difficulty)
This line defines 'a' as a function that requires 2 arguments (choice_category and choice_difficulty)
You need to define the function before you can use it
You program is calling/using the function with this line
superword = a(choice_category, choice_difficulty)
Related
I'm new to programming. I was doing a classic hangman game, but I wanted it to be guessing some character's names from a show (name and surname).
My problem: the dashes print the space between name and surname instead of ignoring it, example:
Secret word: Rupert Giles
How it prints when all the letters are guessed: Rupert_ Giles
(yes, it has a space after the dash)
I've tried:
split()
writing character instead of letter (as space doesn't count
as character in lines 41,42 and 43)
separating the name as ["Name""Surname,
"Name2""Surname1"]
and ['Name'' ''Surname','Name1'' ''Surname1']
What I think it's the problem: the secret "word" is stored in main, and main is in charge of putting dashes instead of the letters, the code of that part goes like this
main = main + "_" + " "
So maybe there's something that should be changed in there so it ignores the spaces
My code:
import random, sys, time, os
def typingPrint(text):
for character in text:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.05)
def typingInput(text):
for character in text:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.05)
value = input()
return value
def clearScreen():
if os.name == 'posix':
_ = os.system('clear')
else:
_ = os.system('cls')
def hangman():
word = random.choice(
["Spike", "Rupert Giles", "Tara Maclay", "Willow Rosenberg", "Buffy Summers", "Xander Harris",
"Wesley Wyndam Price", "Faith Lehane", "Angel", "Darla", "Cordelia Chase", "Dawn Summers",
"Anya Jenkins", "Riley Finn", "Drusilla", "Oz Osbourne", "Kendra Young", "Joyce Summers", "Master",
"Harmony Kendall",
"Jenny Calendar", "Robin Wood", "Jonathan Levinson",
"Ethan Rayne", "Principal Snyder", "Kennedy", "Veruca", "Hank Summers", "Halfrek", "DHoffryn", "Mr Tick"])
validLetters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
turns = 10
guessmade = ''
while len(word) > 0:
main = ""
missed = 0
for character in word:
if character in guessmade.lower() or character in guessmade.upper():
main = main + character
else:
main = main + "_" + " "
if main == word:
print(main)
typingPrint("Congratulations! You win... for now.\nLet's try again")
typingPrint("\nin 3...2...1")
clearScreen()
break
print("\nGuess the word:", main)
guess = input()
if guess in validLetters:
guessmade = guessmade + guess
else:
typingPrint("Enter a valid character: ")
guess = input()
if guess.lower() not in word and guess.upper() not in word:
turns = turns - 1
if turns == 9:
typingPrint("You have 9 turns left")
print("\n -------- this is a ceiling, don't laugh at it")
if turns == 8:
typingPrint("You have 8 turns left")
print("\n -------- ")
print(" O ")
if turns == 7:
typingPrint("You have 7 turns left")
print("\n -------- ")
print(" O ")
print(" | ")
if turns == 6:
typingPrint("You have 6 turns left")
print("\n -------- ")
print(" O ")
print(" | ")
print(" / ")
if turns == 5:
typingPrint("You have 5 turns left")
print("\n -------- ")
print(" O ")
print(" | ")
print(" / \ ")
if turns == 4:
typingPrint("You have 4 turns left")
typingPrint("\nYou are walking on thin ice")
print("\n -------- ")
print(" \ O ")
print(" | ")
print(" / \ ")
if turns == 3:
typingPrint("You have 3 turns left")
typingPrint("\n No pressure")
print("\n -------- ")
print(" \ O / ")
print(" | ")
print(" / \ ")
if turns == 2:
typingPrint("You have 2 turns left")
typingPrint("\nYou call yourself a Buffy fan?")
print("\n -------- ")
print(" \ O / | ")
print(" | O ")
print(" / \ ")
if turns == 1:
typingPrint("You have 1 turn left")
typingPrint("\nYou should re-watch all seasons")
print("\n -------- ")
print(" \ O_|/ ")
print(" | ")
print(" / \ ")
if turns == 0:
typingPrint("You lose, ")
typingPrint(name)
typingPrint("\nThe name was...")
typingPrint(word)
print("\n -------- ")
print(" O_| ")
print(" /|\ ")
print(" / \ ")
typingPrint("Good night")
typingPrint("\nin 3...2...1")
clearScreen()
break
while 1:
name = typingInput("Enter your name: ")
typingPrint("Welcome, ")
typingPrint(name)
typingPrint(". You have been fooled\n")
typingPrint("Now you are my prisioner, my dear ")
typingPrint(name)
typingPrint("\nMwahahaha")
print("\n-------------------------------------")
typingPrint("Try to guess the name of this Buffy's character in less than 10 attempts")
typingPrint("\nIf you can't, you will be hanged")
typingPrint("\nNo pressure, ")
typingPrint(name)
typingPrint("\nOh... and one little, itty bitty thing...")
typingPrint("\nThe names are from Season 1 to 7")
typingPrint("\nGood luck, break a neck... I mean, a leg")
hangman()
print()
You can make this adjustment. Replace
if character in guessmade.lower() or character in guessmade.upper():
main = main + character
With
if character in guessmade.lower() or character in guessmade.upper() or character == " ":
main = main + character
As it stands, you are expecting your users to guess a space character. This new if statement removes that requirement.
Nice. I'd print out guessed letters as well. Think this is what you're going for. You don't have to keep caps in validLetters that way.
for character in word:
if character .lower() in guessmade .lower():
main = main + character
elif character == ' ':
main = main + ' '
else:
main = main + '_' + ' '
main is a terrible variable name, so I'll be using word_as_shown instead. Also, I'll replace guessmade with guessed_letters. If you replace
if guess in validLetters:
guessmade = guessmade + guess
with
if guess in validLetters:
guessed_letters += guess.lower()
and define
def char_as_shown(char):
if char == ' ':
return ' '
if char.lower() in guessed_letters:
return char
return "_"
then you can do
word_as_shown = [char_as_shown(char) for char in word]
I'm writing Connect4 in Python. My problem is the function of player_one and player_two don't seem to be working, so the no piece is drop onto the board after player was asked to give input. I also wonder if my code to return the board after player has dropped is correct; I suspect that my present code doesn't return the board updated with a player's piece but being new, I'm not sure what to do.
Please take a look!
def field(field):
for w in range(14):
if w % 2 == 0:
usable_w = int(w/2)
for h in range(15):
if h % 2 == 0:
usable_h = int(h/2)
if h != 14:
print(field[usable_h][usable_w], end="")
else:
print(" ")
else:
print("|", end="")
else:
print("_"*13)
PlayField = [[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "]]
field(PlayField)
def player_one(field):
MoveColumn = int(input("Enter the column 1 - 7\n"))
MoveRow = 6
for row in PlayField:
if MoveColumn >= 1 and MoveColumn <= 7:
if PlayField[MoveColumn-1][MoveRow] == " ":
PlayField[MoveColumn-1][MoveRow] = "X"
break
MoveRow -= 1
return field(PlayField)
else:
print("Column outside range, please enter valid move")
def player_two(field):
MoveColumn = int(input("Enter the column 1 - 7\n"))
MoveRow = 6
for row in PlayField:
if MoveColumn >= 1 and MoveColumn <= 7:
if PlayField[MoveColumn-1][MoveRow] == " ":
PlayField[MoveColumn-1][MoveRow] = "O"
break
MoveRow -= 1
return field(PlayField)
else:
print("Column outside range, please enter valid move")
def launch_play():
while True:
Player = 1
print("Player's turn", Player)
player_one(field)
player_two(field)
launch_play()
Well, your player_... functions contain suitable statements, but in an unsuitable order; and since they operate on the global PlayField, returning it is pointless. Besides that, it's ugly having two nearly identical functions. A rearranged variant where the only difference between player one and two is passed as an argument (instead of the useless field) works as you expect:
def player(xo):
while (MoveColumn := int(input("Enter the column 1 - 7\n"))) < 1 or \
MoveColumn > 7:
print("Column outside range, please enter valid move")
MoveRow = 6
for row in PlayField:
if PlayField[MoveColumn-1][MoveRow] == " ":
PlayField[MoveColumn-1][MoveRow] = xo
field(PlayField)
break
MoveRow -= 1
In your launch_play loop you can now call
player('X')
player('O')
Now it's up to you to complete the program by checking when the game is over.
I came up with two solutions (before you modified the codes) to prevent players' turn from changing, but which couldn't work:
def player(xo):
while MoveColumn := int(input("Enter the column 1 - 7\n")):
MoveRow = 6
for row in PlayField:
if PlayField[MoveColumn-1][MoveRow] == " ":
PlayField[MoveColumn-1][MoveRow] = xo
field(PlayField)
break
Return True
MoveRow -= 1
else:
print("Column outside range, please enter valid move")
Return False
def launch_play():
while True:
Player = 'X'
print("Player's turn", Player)
player('X')
Player = '0'
print("Player's turn", Player)
player('0')
launch_play()
The other solution is to introduce player variables in the player functions (also didn't work) :
def player(xo):
while MoveColumn := int(input("Enter the column 1 - 7\n")):
MoveRow = 6
Player = 'X'
for row in PlayField:
if PlayField[MoveColumn-1][MoveRow] == " ":
PlayField[MoveColumn-1][MoveRow] = xo
field(PlayField)
break
MoveRow -= 1
Player = '0'
else:
print("Column outside range, please enter valid move")
I am currently learning Python and I am making a tennis coach program. On the option 3 where you can update it is not working as it says nameUnder is not defined in the else statement. Please help as I really don't understand why its not working. I have also tries it without the split but that to doesn't work
import os, sys
print("Please select an option:")
print("[1] Add a student")
print("[2] Read a students data")
print("[3] Update a students data")
print("[4] Delete a students data")
menuSelect = int(input("Make your number selection: "))
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if menuSelect == 1:
amountDone=0
amounttodo=int(input("Enter the number of contestants you would like to add: "))
while amounttodo>amountDone:
ageOne=int(input("Enter the age of the contestant: "))
if ageOne <= 11:
underFile=open("Under11s.txt","a")
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
posUnder=int(input("Input the last position of the student: "))
underFile.write("\n"+str(nameUnder) + " | " + str(genderUnder) + " | " + str(posUnder))
underFile.close()
amountDone=amountDone+1
elif ageOne >= 12:
overFile=open("Over11s.txt","a")
nameOver=input("Enter the first name of the student: ")
genderOver=input("Enter the gender of the student: ")
posOver=int(input("Input the last position of the student: "))
overFile.write("\n"+str(nameOver) + " | " + str(genderOver) + " | " + str(posOver))
overFile.close()
amountDone=amountDone+1
else:
print("Invalid, Please enter a number")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
elif menuSelect == 2:
print("Enter the file you would like to open.")
print("1) Under 11's")
print("2) Over 11's")
fileToOpen=int(input("Enter the number of your selection: "))
if fileToOpen == 1:
f = open("Under11s.txt", "r")
file_contents = f.read()
print(file_contents)
elif fileToOpen == 2:
f = open("Over11s.txt", "r")
file_contents = f.read()
print(file_contents)
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
elif menuSelect == 3:
studentName = input("Enter the student name you are looking for:")
file = open("Under11s.txt","r")
found=False
for line in file:
details = line.split(",")
writefile = open("Under11supdated.txt","a")
details = line.split(",")
if details[0] == studentName:
found=True
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
posUnder=int(input("Input the last position of the student: "))
file.write("\n"+str(nameUnder)[0] + " | " + str(genderUnder)[1] + " | " + str(posUnder)[2])
else:
file.write("\n"+nameUnder[0] + " | " + genderUnder[1] + " | " + posUnder[2])
file.close()
file.close()
os.remove("Under11s.txt")
os.rename("Under11supdated.txt","Under11s.txt")
if found==True:
print("Details updated")
else:
print("That student cannot be found in the file, no changes made")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
else:
print("Sorry, this option is not available yet!")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
nameUnder only gets defined if this statement is true if details[0] == studentName:
Not a 100% of your logic here, but make sure to set nameUnder= "" before the if statement so the variable is declared and can be used in your else clause.
I would recommend you to structure your code with functions for the each options etc., will make it easier to read and possible reuse some of the code.
Partly updated code:
writefile = open("Under11supdated.txt","a")
details = line.split(",")
nameUnder = ""
if details[0] == studentName:
found=True
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
I am making a connect four type game. I am trying to set up the simple playability of the game. I don't get an error, but it does keep sending me into a input when I want it to print out the board. When I type in a number for the column, it doesn't print anything, it just gives me another input I should fill, this continues until i exit the program.. I am trying to stay away from classes, given that I am not very good at programming these yet. I would like to know why this is happening, and what to do to fix it, or if I just need to reprogram the whole thing.
a = [" ", " ", " ", " ", " ", " ", " "]
b = [" ", " ", " ", " ", " ", " ", " "]
c = [" ", " ", " ", " ", " ", " ", " "]
d = [" ", " ", " ", " ", " ", " ", " "]
e = [" ", " ", " ", " ", " ", " ", " "]
f = [" ", " ", " ", " ", " ", " ", " "]
board = [a, b, c, d, e, f] # sets up the board
print("What is player 1's name?")
player1 = input()
print("What is player 2's name?")
player2 = input()
plays = 0
def print_board(): # prints the board
p = 0
for x in board:
for i in x:
print(i, end=" | ")
print()
p += 1
if p != 6:
print("- "*15)
else:
print()
def win(): # defines a boolean if one player has won
i = 0
k = 0
while i != 5:
while k != 6:
if board[i][k] == "o" or board[i][k] == "x":
if board[i+1][k] == board[i][k] == board[i+2][k] == board[i+3][k]:
return False
elif board[i][k] == board[i][k+1] == board[i][k+2] == board[i][k+3]:
return False
elif board[i][k] == board[i+1][k+1] == board[i+2][k+2] == board[i+3][k+3]:
return False
elif board[i][k] == board[i-1][k-1] == board[i-2][k-2] == board[i-3][k-3]:
return False
else:
return True
def play(): # defines the part you play.
if plays % 2 == 0:
player = "o"
else:
player = "x"
print_board()
x = int(input("Where would you like to put your chip?"))
i = 0
while i < 5:
if board[i][x] == " ":
if board[i+1][x] == "x" or board[i+1][x] == "o":
board[i][x] = player
print_board()
if win():
print(player+" won!")
play()
play() # runs the script
try this for your play loop - hopefully it will help you fix the win check also:
def play(): # defines the part you play.
plays = 0
while True:
if plays % 2 == 0:
player = "o"
else:
player = "x"
x = int(input("Where would you like to put your chip?"))
i = 0
for i in range(5):
if board[i][x] == " ":
if board[i+1][x] == "x" or board[i+1][x] == "o":
board[i][x] = player
else:
board[5][x] = player
print_board()
#if win():
# print(player+" won!")
# break
plays += 1
print_board()
play() # runs the script
i commented out the win check because it doesn't work yet
So, I've finished my Hangman project for a coding class and it's stuck in a loop where it just keeps asking if you want to play, after that it defines the word to play but it also TELLS you which word to play you're going to play. I think the chained whiles and ifs have some wrong variables.
So, I beg for your help.
__author__ = 'Rodrigo Cano'
#Modulos
import random
import re
#Variables Globales
intentos = 0
incorrectos = 0
palabras = [(1,"disclosure"),(1,"thenational"),(1,"foals"),(1,"skepta"),(1,"shamir"),(1,"kanye"),
(1,"fidlar"),(1,"lcdsoundsystem"),(1,"lorde"),(1,"fkatwigs"),(1,"miguel"),(1,"rtj"),
(1,"boniver"),(1,"strokes"),(2,"vaporwave"),(2,"witchouse"),(2,"shoegaze"),(2,"memerap"),
(2,"paulblartisoursaviour"),(3,"glockenspiel"),(3,"aesthetic"),(3,"schadenfreude"),
(3,"bonvivant"),(3,"swag"),(3,"jue")]
Ascii_Art =[""]
Dibujo = ' '
palabra_a_jugar = ''
Array_Palabra = []
Nuevas_Letras = ''
letras = []
Vidas = 0
i = len(Array_Palabra)
#Funciones
def Definir_Palabra():
eleccion = int(input("Bienvenido, que categoria quiere usar:"
'\n'"1 - Musica que Escuche Mientras Lo Hacia"
'\n'"2 - Generos Musicales"
'\n'"3 - Palabras Pretenciosas"))
palabras_escogidas = [i for i in palabras if eleccion in i ]
palabra_a_jugar = str(palabras_escogidas[random.randint(0,len(palabras_escogidas))].__getitem__(1))
Array_Palabra = len(palabra_a_jugar) * ['*']
return palabra_a_jugar, Array_Palabra
def Letras_En_Palabra(letra):
letras = [i for i, x in enumerate(palabra_a_jugar) if x == letra]
for i in range (0, len(letras)):
Array_Palabra[letras] = letra
return letras,Array_Palabra
def Letras_Jugadas(letra):
for i in range(0,len(Nuevas_Letras)):
Nuevas_Letras = re.findall(letra,Nuevas_Letras[i])
if Nuevas_Letras != []:
return 1
return Nuevas_Letras
def Eleccion():
Choice = input("Quiere Jugar?")
if Choice == 'si':
Choice = 1
elif Choice == 'no':
Choice = 0
return Choice
# Juego
Choice = Eleccion()
def Juego(Choice):
i = len(Array_Palabra)
while Choice == 1:
print(Definir_Palabra())
while i != 0 :
tiro = str.lower(input("adivine una letra"))
if Letras_Jugadas(tiro) != 1:
Nuevas_Letras = Nuevas_Letras + tiro
letras = Letras_En_Palabra(tiro)
if Letras_Jugadas(tiro) != []:
i = len(letras) - 1
print("Letras Utilizadas",Nuevas_Letras)
print(Letras_En_Palabra(tiro))
else:
Vidas = Vidas + 1
Dibujo += Ascii_Art[Vidas]
print("WROOOONG")
print(Dibujo)
print("Letras Utilizadas",Nuevas_Letras)
if Vidas ==9:
i = 0
else:
print("Letra ya Juagada",Nuevas_Letras)
Eleccion()
Juego(Choice)
The last line in your Juego should be Choice = Eleccion(), otherwise, you're not actually changing the value of Choice, so the loop continues indefinitely.
def Juego(Choice):
i = len(Array_Palabra)
while Choice == 1:
print(Definir_Palabra())
while i != 0 :
tiro = str.lower(input("adivine una letra"))
if Letras_Jugadas(tiro) != 1:
Nuevas_Letras = Nuevas_Letras + tiro
letras = Letras_En_Palabra(tiro)
if Letras_Jugadas(tiro) != []:
i = len(letras) - 1
print("Letras Utilizadas",Nuevas_Letras)
print(Letras_En_Palabra(tiro))
else:
Vidas = Vidas + 1
Dibujo += Ascii_Art[Vidas]
print("WROOOONG")
print(Dibujo)
print("Letras Utilizadas",Nuevas_Letras)
if Vidas ==9:
i = 0
else:
print("Letra ya Juagada",Nuevas_Letras)
"""
>>>> CHANGED <<<<
"""
Choice = Eleccion()
Otherwise, the way you had it simply calls the function Eleccion but doesn't return the value to the Choice variable in scope of Juego function.
Just need to indent :)
import random
# defining the main method
def main():
print "Hello Welcome to Python Hangman!!!"
random_word()
user_input()
# defining the dictionary_list to be used as the guessing word
def random_word():
dictionary_list= ["ant", "bath", "car", "dog", "electric", "foil", "grape", "heat", "ice", "jolly",
"knight", "lemon", "money", "need", "open", "park", "quote", "rough", "salty",
"teach", "under", "village", "warmth", "xavier", "yelp", "zipper"]
# making rand global so it can be used within deifferent functions
global rand
# randomly choosing a word from the dictionary_list and assign to the variable rand
rand = random.choice(dictionary_list)
return rand
# user guessing
def user_input():
guesses = 0
wrong_guess = 0
guess_left = 10
correct_letters_list = ""
wrong_letters_list =""
print "You have \033[1;34;15m 10 \033[0;30;15m guesses"
#getting the length of the word
length = len(rand)
print "The word is: " + "\033[1;35;15m" + str(length) + "\033[0;30;15m" + " characters long"
# loops around until the user has used all their 6 guesses are used up
while guesses < 10 :
guess = raw_input("Guess a Letter [a-z]: ").lower()
# stop case sensitivity
# if the letter guessed by the user is in rand string print correct else print wrong
if guess in rand:
correct_letters_list += guess
print "\033[1;32;15mcorrect"
print "correct letters:"
print "\033[0;30;15m" + correct_letters_list
print "incorrect letters:"
print "\033[0;30;15m" + wrong_letters_list
# each time the user guesses + 1 to the guesses tally
guesses +=1
guess_cal = guess_left - guesses
print "You have: " + str(guess_cal) + " guesses left"
# if rand contains guess more than once tell user
if rand.count(guess) > 1 :
print "The word contains the letter " + str(guess) + " " + "\033[1;36;15m" + str(rand.count(guess)) + "\033[0;30;15m" + " times"
else:
wrong_letters_list += guess
print "\033[1;31;15mwrong"
print "incorrect letters:"
print "\033[0;30;15m" + wrong_letters_list
print "correct letters:"
print "\033[0;30;15m" + correct_letters_list
guesses += 1
guess_cal = guess_left - guesses
print "You have: " + str(guess_cal) + " guesses left"
wrong_guess += 1
if wrong_guess == 1:
print "________ "
print "| | "
print "| "
print "| "
print "| "
print "| "
if wrong_guess == 2:
print "________ "
print "| | "
print "| 0 "
print "| "
print "| "
print "| "
if wrong_guess == 3:
print "________ "
print "| | "
print "| 0 "
print "| / "
print "| "
print "| "
if wrong_guess == 4:
print "________ "
print "| | "
print "| 0 "
print "| /| "
print "| "
print "| "
if wrong_guess == 5:
print "________ "
print "| | "
print "| 0 "
print "| /|\ "
print "| "
print "| "
if wrong_guess == 6:
print "________ "
print "| | "
print "| 0 "
print "| /|\ "
print "| / "
print "| "
if wrong_guess >= 7:
print "________ "
print "| | "
print "| 0 "
print "| /|\ "
print "| / \ "
print "| "
choice = raw_input("Do you wish to guess the word? (Y/N): ").lower()
if choice == 'y':
word = raw_input("Please enter the word: ").lower()
if word == rand:
print "Well Done you Guessed Correctly, the word was: " + rand
# if the user has guessed correctly + 10 to the guesses tally to end the game
guesses += 10
else:
print "Incorrect, Game Over!! The word was: " + rand
guesses += 10
# if user chooses n continue with the game
if choice == 'n':
continue
# if the user has used up all their 10 guesses print Game Over!!
if guesses == 10:
print "End of Game you ran out of guesses!!!"
if __name__ == "__main__":
main()