Im doing a little home project since I'm learning python (beginner) and I made my self a Russian roulette game and it comes up with Unexpected EOF while Parsing on the last line. So if some could help me out on whats going wrong I will be very thankful.
import random
print ("Welcome to Russian Roulette without guns :/ ")
amount = input("How many players? 2 or 3 or 4:")
if amount == ("2"):
print ("Player 1 Name")
player_1 = input(" ")
print ("Player 2 Name")
player_2 = input(" ")
print (player_1)
enter = input("Click Enter:")
if enter == (""):
number = random.randint(1, 2)
print (number)
if number == 1:
print (player_1)
print ("You dead")
print ("---------")
print (player_2)
print ("You win")
else:
print (player_2)
enter_2 = input("Click Enter:")
if enter_2 == (""):
number_2 = random.randint(1, 2)
if number_2 == 1:
print (player_2)
print ("You Lose")
print ("---------")
print (player_1)
print ("You win")
elif amount == ("3"):
print ("Player 1 Name")
player_1 = input(" ")
print ("Player 2 Name")
player_2 = input(" ")
print ("Player 3 Name ")
player_3 = input(" ")
print (player_1)
enter_3 = input("Click Enter:")
if enter_3 == (""):
number_3 = random.randint(1, 1)
print (number)
if number == 3:
print (player_1)
print ("You Dead")
print ("Your Out")
print ("-------------")
print ("{0}, {1} You are still in".format(player_1, player_2)
On the last line, you are missing a closing parenthesis. It should be:
print ("{0}, {1} You are still in".format(player_1, player_2))
EOF is end of file so it usually an an unexpected termination of the program, which is most likely caused by one of a few things, in python: if you missed closing parentheses, or a missing ; in the last line/ line before (so it runs as one line with out the ;). however i can tell you that you are missing closing parentheses at the end of the last print statement. also just a small improvement i would suggest, comment your code python is quite easy to read but its good practice for languages that are not as easy to read.
Related
I'm trying to write an if statement where if the user enters "yes" a game runs but when I cannot figure out how to do this, I can't find it online.
userName = input("Hello, my name is Logan. What is yours? ")
userFeel = input("Hello " + userName + ", how are you? ")
if userFeel == "good":
print ("That's good to hear")
elif userFeel == "bad":
print ("Well I hope I can help with that")
q1 = input("Do you want to play a game? ")
if q1 == "yes":
print ("Alright, lets begin")
import random
print ("This is a guessing game")
randomNumber = random.randint(1, 100)
found = False
yes = "yes"
while not found:
userGuess = input('Your Guess: ') ; userGuess = int(userGuess)
if userGuess == randomNumber:
print ("You got it!")
found = True
elif userGuess>randomNumber:
print ("Guess Lower")
else:
print ("Guess Higher")
elif game == "no":
print ("No? Okay")
q2 = input("What do you want to do next? ")
This is because you have named both your variable for your input "game" and your function call "game". rename one or the other and your code should work as intended.
If you are using Python2.*, You should use raw_input instead of input.
And no matter what version of Python you are using, you should not use the same name for both the function and your variable.
This is my first year programming with Python.
I am trying to create a hangman game.
So my questions: how do I check for
If the person is guessing a letter that has already been guessed and where to include it.
Check they are inputting a valid letter not multiple letters or a number.
What happens if it's a word such as 'Good' and they guess an 'o' at the moment my code breaks if this is the case. Also where on Earth would this be included in the code?
Here is my code
import random
import math
import time
import sys
def hangman():
if guess == 5:
print " ----------|\n /\n|\n|\n|\n|\n|\n|\n______________"
print
print "Strike one, the tigers are getting lonely!"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 4:
print " ----------|\n / O\n|\n|\n|\n|\n|\n|\n______________"
print
print "Strike two, pressure getting to you?"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 3:
print " ----------|\n / O\n| \_|_/ \n|\n|\n|\n|\n|\n______________"
print
print "Strike three, are you even trying?"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 2:
print " ----------|\n / O\n| \_|_/ \n| |\n|\n|\n|\n|\n______________"
print
print "Strike four, might aswell giveup, your already half way to your doom. Oh wait, you can't give up."
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 1:
print " ----------|\n / O\n| \_|_/ \n| |\n| / \\ \n|\n|\n|\n______________"
print
print "One more shot and your done for, though I knew this would happen from the start"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 0:
print " ----------|\n / O\n| \_|_/ \n| |\n| / \\ \n| GAME OVER!\n|\n|\n______________"
print "haha, its funny cause you lost."
print "p.s the word was", choice
print
words = ["BAD","RUGBY","JUXTAPOSED","TOUGH","HYDROPNEUMATICS"]
choice = random.choice(words)
lenWord = len(choice)
guess = 6
guessedLetters = []
blanks = []
loading = ".........."
print "Loading",
for char in loading:
time.sleep(.5)
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.5)
print "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
print "Great I'm glad to see you have finally woken."
time.sleep(1)
raw_input("Did you have a nice journey? ")
time.sleep(2)
print """
Oh wait, I don't care.
I have brought you to this island simply for my amusment. I also get paid to do this.
"""
time.sleep(2)
print"""
Don't worry this isn't all for nothing.
I'm sure the tigers will enjoy your company.
"""
time.sleep(2)
print"""
Hold on, let us make things interesting.
"""
time.sleep(2)
print "I will let you live if you complete an impossible game!"
time.sleep(2)
print "A game know as hangman!"
time.sleep(2)
print "HAHAHAHAHAH, I am so evil, you will never escape!"
time.sleep(2)
print "Enjoy your stay :)"
time.sleep(1)
print
print "Alright lets begin! If you wish to guess the word type an '!' and you will be prompted"
time.sleep(.5)
print
for s in choice:
missing = choice.replace(choice, "_")
blanks.append("_")
print missing,
print
time.sleep(.5)
while guess > 0:
letterGuess = raw_input("Please enter a letter: ")
letterGuess = letterGuess.upper()
if letterGuess == "!":
print "If you guess the FULL word correcly then you win, if incorrect you die. Simple."
fullWordGuess = raw_input("What is the FULL Word? ")
fullWordGuess = fullWordGuess.upper()
if fullWordGuess == choice:
print "You must have hacked this game"
time.sleep(.5)
print "Looks like you beat an impossible game! \nGood Job \nI'll show myself out."
break
else:
print "You lost, I won, you're dead :) Have a nice day!"
print "P.S The word was ", choice
break
else:
print
if letterGuess in choice:
location = choice.find(letterGuess)
blanks.insert(location, letterGuess)
del blanks[location+1]
print " ".join(blanks)
guessedLetters.append(letterGuess)
print
print "You have guessed the letters- ", guessedLetters
if "_" not in blanks:
print "Looks like you beat an impossible game! \nGood Job \nI'll show myself out."
break
else:
continue
else:
guessedLetters.append(letterGuess)
guess -= 1
hangman()
I did not really follow your code since there seems to be something wrong with your indentation, and the many print's confused me a little, but here is how I would suggest soving your Questions:
1.1. Create a list of guessed characters:
guessed_chars = []
if(guess in guessed_chars):
guessed_chars.append(guess)
#do whatever you want to do with the guess.
else:
print("You already guessed that.")
#do what ever you want to do if you already guessed that.
1.2 Lets say the word the player has to ges is word = "snake". To get the indices (since a string is just a list of charcters in python, only that it is immutable) where the guessed letter is in the word you could then use something like:
reveal = "_"*len(word)
temp = ""
for i, j in enumerate(word):
if j == guess:
temp += guess
else:
temp += reveal[i]
reveal = temp
print(reveal)
Maybe not fancy but it should work:
if (guess not in [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z]):
with my suggestion for 1.2 you would just have to check if(word==reveal): no problem with duplicate charcters.
Since I am just a hobbyist there would probably be a more professional way though.
Next time maybe splitting up your question and first looking them up individually would be better, since I am pretty sure that at least parts of your questions have been asked before.
I've looked at the similar questions but all were either a description without indentation after an if statement, or a weird mixture of spaces and tabs. I have tried removing all of the tabs and using 4 spaces and also tried with all tabs, I'm just stuck now. I've tried retyping the whole thing but I must be missing something. Any help would be greatly appreciated
EDIT: Posting the whole thing as people are getting confused about the functions which I didn't post
from sys import exit
class player:
str = 0
wep_dam = 0
dam = str + wep_dam
cha = 0
sne = 0
arm = 0
max_life = 10
points_remaining = 0
cave_save = False
cave_fork_save = False
dragon_save = False
def exit_beach():
print "Walking further up the beach from water, you see a cave."
print "Above the cave hangs a warning sign, it reads:\n"
print "\"DANGER: Tresspassers will be killed and eaten\""
ans = raw_input("Ignore the warning and enter the cave?\n\n1. Enter the cave\n2. Continue walking\n\n> ")
if ans == "1":
cave()
elif ans == "2":
troll()
else:
print "Error, you didn't enter 1 or 2\n"
def shadow_figure():
print "\n\nYou approach the figure, who remains silent."
print "As you get closer you realise he has bag at his feet."
print "Mysterious figure: \"You may choose only one.\""
print "You look into the bag, and see a shiny sword on top of a large steel shield."
ans = raw_input("Do you: \n1. Take the sword \n2. Take the shield \n3. Take the whole bag and run \n4. Walk away without taking anything\n> ")
if ans == "1":
print "The sword gives you an extra 3 damage"
player.wep_dam += 3
exit_beach()
elif ans == "2":
print "The shield gives you 3 armor, but it's so heavy it reduces your sneak by 1"
player.arm += 3
player.sne -= 1
exit_beach()
elif ans == "3":
dungeon("You get about 10 feet away with the bag before bony fingers grip your throat and choke you unconscious")
elif ans == "4":
exit_beach()
else:
print "Error, please enter anumber between 1 and 4"
def beach():
print "\n\nYou wake up on a beach with no idea how you got there. \nYou see a shadowy figure close to the water."
ans = raw_input("Do you: \n1. Approach him \n2. Go the other way\n> ")
if ans == "1":
shadow_figure()
elif ans == "2":
exit_beach()
else:
print "Please enter either 1 or 2"
def dungeon(why):
print why
if not player.cave_save and not player.dragon_save and not player.cave_fork_save:
print "Unfortunately you didn't get far enough to continue from a saved point, \n would you like to restart from the beginning? (Yes/No)"
ans = raw_input("> ")
ans = ans.lower()
if ans == "yes":
reset_stats()
start()
else:
end()
elif player.cave_save and not player.dragon_save and not player.cave_fork_save:
print "Would you like to continue from the cave entrance or start over?"
print "1. Cave entrance\n2. Start over\n3. Exit game"
ans = raw_input("> ")
if ans == "1":
cave()
elif ans == "2":
reset_stats()
start()
else:
end()
elif player.cave_save and player.cave_fork_save and not player.dragon_save:
print "Would you like to continue from the cave entrance, the cave fork, or start over?"
print "1. Cave entrance\n2. Cave fork\n3. Start over\n4. Exit game"
ans = raw_input("> ")
if ans == "1":
cave()
elif ans == "2":
cave_fork()
elif ans == "2":
reset_stats()
start()
else:
end()
else:
print "Havent done this part yet"
def reset_stats():
str = 0
wep_dam = 0
dam = str + wep_dam
cha = 0
sne = 0
arm = 0
max_life = 10
points_remaining = 10
print "\n\n\n\nGame Reset\n\n\n\n"
def end():
print "Thank you for playing"
exit(0)
def start():
print "You are an adventurer, your stats are currently:"
print "Strength: %d \nCharisma: %d \n Sneak: %d" % ( player.str, player.cha, player.sne)
print "Strength determines your damage, charisma determines your chance of pursuasion, \nand sneak determines whether or not you can go get past enemies without being detected"
print "you have 10 points available to spend, to spend a point, simply type the number which corresponds\nwith the skill and hit enter"
print "\n\n1. Strength \t2. Charisma \t3. Sneak\n"
player.points_remaining = 10
while player.points_remaining > 0:
ans = raw_input("Choose a skill: ")
if ans == "1":
player.str += 1
player.points_remaining -= 1
print "Strength is now %d" % ( player.str)
print "%d points remaining\n" % ( player.points_remaining)
elif ans == "2":
player.cha += 1
player.points_remaining -= 1
print "Charisma is now %d" % ( player.cha)
print "%d points remaining\n" % ( player.points_remaining)
elif ans == "3":
player.sne += 1
player.points_remaining -= 1
print "Sneak is now %d" % ( player.sne)
print "%d points remaining\n" % (player.points_remaining)
else:
print "Error, please enter a number from 1 to 3\n"
print "Your stats are now: "
print "Strength: %d \nCharisma: %d \n Sneak: %d\n\n" % ( player.str, player.cha, player.sne)
print "Is this OK? Or would you like to restart?\n"
ans = raw_input("1. Continue \n2. Restart\n> ")
if ans == "1":
print "Game will now begin...."
beach()
elif ans == "2":
ans = raw_input("Are you sure? Yes/No\n> ")
ans = ans.lower()
if ans == "yes":
reset_stats()
start()
else:
beach()
else:
print "Error, please enter 1 or 2"
start()
Corrected code:
def shadow_figure():
print "\n\nYou approach the figure, who remains silent."
print "As you get closer you realise he has bag at his feet."
print "Mysterious figure: \"You may choose only one.\""
print "You look into the bag, and see a shiny sword on top of a large steel shield."
ans = raw_input("Do you: \n1. Take the sword \n2. Take the shield \n3. Take the whole bag and run \n4. Walk away without taking anything\n> ")
if ans == "1":
print "The sword gives you an extra 3 damage"
wep_dam += 3
exit_beach()
elif ans == "2":
print "The shield gives you 3 armor, but it's so heavy it reduces your sneak by 1"
arm += 3
sne -= 1
exit_beach()
elif ans == "3":
dungeon("You get about 10 feet away with the bag before bony fingers grip your throat and choke you unconscious") #Should dungeon() be print instead?
elif ans == "4":
exit_beach()
else:
print "Error, please enter a number between 1 and 4"
See Vaibhav Mule's answer. You were using the assignment operator on input 3 and 4, rather then the comparison operator. There might be more wrong here, but it's hard to tell without the rest of your code. Also I'm not sure what your dungeon() function does, but you probably meant print?
Please also look at elif block, where you suppose to do.
elif ans == "3": # make sure you have '==' operator here.
elif ans == "4":
The error was pointing to line 20, which in this case would be line 1.
The error was in the function exit_beach() that was being called and not actually within this function.
As soon as I added the correct indentation to function exit_beach() the error disappeared.
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.
If you do not guess the number correctly on the first try, the program will run until you run out of guesses regardless if you guessed the correct number. Is there a problem with my while loop or if statements?
while True:
try:
Guessed_number = int(raw_input("What is your guess? \n"))
except ValueError:
print("Sorry, that is not a valid guess. Please guess again.")
continue
else:
break
def Number_guesser(Guessed_number):
guesses= 3
while guesses > 0:
if Random_number == Guessed_number:
print "Congratualations! You won :)"
break
elif Guessed_number > Random_number:
print "You guessed higher than the number. Try again! \n"
print Random_number
Guessed_number= raw_input()
guesses= guesses-1
elif Guessed_number < Random_number:
print "You guessed lower than the number. Try again! \n"
Guessed_number= raw_input()
guesses= guesses-1
if guesses == 3:
print "You have 3 guesses left!"
elif guesses == 2:
print "You have 2 guesses left!"
elif guesses == 1:
print "You have 1 guess left!"
elif guesses == 0:
print "You ran out of guesses :( \n The correct answer was........*drum roll*"
print Random_number
print Number_guesser(Guessed_number)`
I figured out that my raw_input needed to be an integer every time I prompted the player to guess again.
Guessed_number= int(raw_input())