I am just exploring the vast language of python. I'm heavily relying on the inbuilt error-decetion and googling to debug my programs. I had no luck this time around. Thank you for your time!
I am getting
"invalid syntax at line 5"
Here is my python-code of a simple HANGMAN-game:
import random
def __secretword__():
secret_word = word_list[random.randomint(len(word_list))
return secret_word #THIS IS LINE 5
def __ask__():
ans = input("Would you like to play more? (yes/no): ")
if ans == "yes"
__secretword__()
else:
print(":(")
__secretword__()
word_list = ["nei", "brun", "ja", "smile", "glad", "gal"]
secret_word = secret_word
sw_list = list(secret_word)
guess_lines = ["_"] * len(secret_word)
mistakes = []
lives = 2 * len(secret_word)
print(guess_lines)
user_guess = input("Guess a letter: ")
while(lives != 0)
if user_guess in sw_list:
i = sw_list.index(user_guess)
del guess_lines[i]
guess_lines.insert(i, user_guess)
print(guess_lines)
print("Lives: ", lives)
print("Mistakes: ", mistakes)
if "_" not in guess_lines:
break
else:
mistakes.append(user_guess)
print(guess_lines)
lives = lives - 1
print("Lives: ", lives)
print(mistakes)
__ask__()
Your problem is that the line before return is missing its closing square bracket ]. So Python thinks you're still inside the brackets when you get to line 5, and placing return inside brackets is a syntax error.
This is a fairly common problem - if you get a syntax error on a line that looks fine, it's often worthwhile to look at the previous line, and see if your line might be being considered part of that.
Related
The following code will not run nor will it show an error message. Please help. Also, how would I add a function to display only the output of this code?
def main():
s= ""
phrase=""
programdescription(s)
userinput(phrase)
#This function displays the program description
def programdescription(s):
s = print("This program determines if a word, phrase, or sequence can be read the same backward as forward.")
#This function requests user input for analysis
def userinput(phrase):
phrase = input("Enter a word or phrase: ")
def s_phrase(phrase):
phrase = phrase.upper()
strippedPhrase = ""
for char in phrase:
if (48 <= ord(char) <= 57) or (65 <= ord(char) <= 90):
strippedPhrase += char
flag = True
n = len(strippedPhrase)
for j in range(int(n / 2)):
if strippedPhrase[j] != strippedPhrase[n - j - 1]:
flag = False
break
if flag:
print(phrase, "is a palindrome.")
else:
print(phrase, "is not a palindrome.")
main()
Ok, problem 1 is you never call s_phrase.
Problemo 2 is that the phrase variable can't be seen by s_phrase.
Problem numero C is that your indentation is messed up.
Issue 4 is more the fact that this seems like a very 'C' way of tackling the challenge. Borrowing from Spade, here is a more succinct way of doing it that is formatted to your original program.
def main():
s= ""
phrase=""
programdescription(s)
s_phrase(phrase)
#This function displays the program description
def programdescription(s):
s = print("This program determines if a word, phrase, or sequence can be read the same backward as forward.")
#This function requests user input for analysis
def s_phrase(phrase):
phrase = input("Enter a word or phrase: ")
phrase = phrase.upper()
r_phrase = phrase[::-1]
print(r_phrase)
if phrase == r_phrase:
print(phrase, "is a palindrome.")
else:
print(phrase, "is not a palindrome.")
main()
I'm writing my first short programs with Python. This program should stop after the third wrong guess. The program works as expected with the first question, and stops itself after three wrong guesses.
However, I cannot understand why, with the second question, after the third wrong guess, the first question is repeated.
easy_text = '''Hello __1__!' In __2__ this is particularly easy; all you
have to do is type in: __3__ "Hello __1__!" Of course, that isn't a very
useful thing to do. However, it is an example of how to output to the user
using the __3__ command, and produces a program which does something, so it
is useful in that capacity..'''
def split_string():
global easy_text_splitted
easy_text_splitted = easy_text.split(" ")
return None
def level1():
print """You will get 3 guesses per problem
The current paragraph reads as such:"""
print easy_text
return first_question(3)
def first_question(guesses):
while guesses > 0:
split_string()
first_answer = raw_input("What should be substituted in for __1__?")
if first_answer.lower() == "world":
easy_text_splitted[1] = first_answer
easy_text_splitted[19] = first_answer
new_easy_text = " ".join(easy_text_splitted)
print new_easy_text
second_question(3)
else:
guesses -= 1
print "That's not the answer I expected. You have " +
str(guesses) + " guess(es) left"
return first_question(guesses)
def second_question(guesses):
while guesses > 0:
split_string()
second_answer = raw_input("What should be substituted in for 2?")
if second_answer.lower() == "python":
easy_text_splitted[4] = second_answer
new_easy_text = " ".join(easy_text_splitted)
print new_easy_text
else:
guesses -= 1
print "That's not the answer I expected. You have \n " +
str(guesses) + " guess(es) left"
return second_question(guesses)
def level_selection(index):
level = raw_input("Choose the desired level of difficulty: easy, \n
medium, or hard ")
if level.lower() == "easy":
return level1()
if level.lower() == "medium":
return level2
if level.lower() == "hard":
return level3
else:
print "Error"
index -= 1
if index > 0:
return level_selection(index)
return "Bye!"
print level_selection(3)
level2 = "You selected medium"
level3 = "You selected hard"
Whatever the value of guesses was in first_question when second_question was called, it is the same when it returns, so the loop continues, and repeats the first question.
Using a debugger will help you follow how this works.
Thank you #Idor I am making some progress but I am not 100% there yet. Right now my code looks as following:
def easy_game(easy_text, parts_of_speech1):
replaced = []
easy_text = easy_text.split()
i = 0
for word in easy_text:
replacement = word_in_pos_easy(word, parts_of_speech1)
if replacement != None:
user_input = raw_input("Type in: " + replacement + " ")
word = word.replace(replacement, user_input)
while word != solutions[i]:
print "Sorry, you are wrong"
user_input = raw_input("Type in: " + replacement + " ")
print i
i = i + 1
print i
replaced.append(word)
else:
replaced.append(word)
replaced = " ".join(replaced)
print
#time.sleep(1)
print "Ok, lets see your results. Does it make sense?"
print
#time.sleep(1)
return replaced
print
#time.sleep(1)
print easy_game(easy_text, parts_of_speech1)
You can see I added the while loop. I also added an index and for troubleshooting I added print i to see what the program is doing. It still confuses me a bit or doesn't work as I would expect it. But being a newbie to programming my expectations are probably wrong. Here's what's happening:
When you enter the correct answer the program continues to question 2 and also increases i by 1
This works from beginning to end if you enter everything correctly
When you enter the wrong answer you are prompted to enter it again. Good!
However the user then gets stuck in this very question although i has been increased to the right value.
I don't really understand why the user would be stuck at this point when i has been increased, i.e. we would check at the right position in the list for the correct answer.
This is the full code of the game. I can successfully run it on my Mac but see the above behavior. Any thoughts on this by any chance? thanks in advance!
parts_of_speech1 = ["Word1", "Word2", "Word3", "Word4"]
# The following is the text for the easy text..
easy_text = "Python is a Word1 language that provides constructs intended to enable clear programs on both small and large scale. Python implementation was started in December Word2 by Guido von Rossum. The most simple Word3 in Python is Word4 and normally used at the beginning to tell Python to write 'Hello World' on the screen."
solutions = ["programming", "1989", "function", "print"]
# Checks if a word in parts_of_speech is a substring of the word passed in.
def word_in_pos_easy(word, parts_of_speech1):
for pos in parts_of_speech1:
if pos in word:
return pos
return None
# Plays a full game of mad_libs. A player is prompted to replace words in the easy text,
# which appear in parts_of_speech with their own words.
def easy_game(easy_text, parts_of_speech1):
replaced = []
easy_text = easy_text.split()
i = 0
for word in easy_text:
replacement = word_in_pos_easy(word, parts_of_speech1)
if replacement != None:
user_input = raw_input("Type in: " + replacement + " ")
word = word.replace(replacement, user_input)
while word != solutions[i]:
print "Sorry, you are wrong"
user_input = raw_input("Type in: " + replacement + " ")
print i
i = i + 1
print i
replaced.append(word)
else:
replaced.append(word)
replaced = " ".join(replaced)
print
#time.sleep(1)
print "Ok, lets see your results. Does it make sense?"
print
#time.sleep(1)
return replaced
print
#time.sleep(1)
print easy_game(easy_text, parts_of_speech1)
I am building out a quiz based on raw_input using several different list operations. I also want to validate the user input against a list before moving on to the next question in the quiz.
The function currently looks like this:
def play_game(ml_string, parts_of_speech):
replaced = []
ml_string = ml_string.split()
for word in ml_string:
replacement = word_in_pos(word, parts_of_speech)
if replacement != None:
user_input = raw_input("Type in a: " + replacement + " ")
word = word.replace(replacement, user_input)
if word != solution_list1[0]:
print "Sorry, you are wrong. Try again!"
replaced.append(word)
else:
replaced.append(word)
replaced = " ".join(replaced)
return replaced
In Line 9 I am checking against the List containing the solution words. Whereas the validation itself works the function just continues to the next question but I need it to repeat the question until getting the correct answer. I tried to reposition the different lines but simply can't get my head around it at this point in time. Where or how do I need to place the validation of the user input correctly to prompt the user for the same question again?
It seems to me that what you are looking for is a while loop.
Instead of:
if word != solution_list1[0]:
print "Sorry, you are wrong. Try again!"
Try:
while word != solution_list1[0]:
print "Sorry, you are wrong. Try again!"
user_input = raw_input("Type in a: " + replacement + " ") # ask the user again
word = word.replace(replacement, user_input)
This way the user will have to answer the question again (raw_input) until he gets it right.
I've been asked for my A Level computing to create a text based hangman game. For some reason, when the "guessword" is displayed, it contains an additional character at the end, which cannot be solved, and therefore makes the game unwinnable. This only happens on a few circumstances, not every word in the list has this additional character.
Here is the python code:
import random
class Hangman():
def Playing(self):
category = raw_input("Please select a category from; EuroCapitals; PremTeams; FruitAndVeg")
again = True
while again:
guessword = open(category + ".txt", "r").readlines()[random.randint(0,9)]
board = "*" * (len(guessword) - 1)
alreadySaid = set()
mistakes = 7
print(" ".join(board))
guessed = False
while not guessed and mistakes > 0:
whatplayersaid = raw_input("Guess a letter: ")
if whatplayersaid in guessword:
alreadySaid.add(whatplayersaid)
board = "".join([char if char in alreadySaid else "*" for char in guessword])
if board == guessword:
guessed = True
else:
mistakes -= 1
print("Nope.", mistakes, "mistakes left.")
print(" ".join(board))
again = (input("Again [y/n]: ").lower() == 'y')
Hangman().Playing()
And the list of words in "EuroCapitals.txt" is as follows:
london
paris
madrid
berlin
moscow
rome
amsterdam
bern
zagreb
stockholm
Any help would be greatly appreciated.
Most likely it's a \n character (or maybe some extra whitespace?) from the file -- readlines() will preserve them if they are in the file. So, you want to .rstrip() your guessword, e.g.:
guessword = open(category + ".txt", "r").readlines()[random.randint(0,9)].rstrip()
As an aside, creating an anonymous file object like this generally isn't a good idea, because it won't be closed right away. You're better off using a with statement:
with open(category + ".txt", "r") as f:
guessword = f.readlines()[random.randint(0,9)].rstrip()
and you could further refine it with
with open(category + ".txt", "r") as f:
guessword = random.choice(f.readlines()).rstrip()
I am reading the book "Python Programming for the Absolute Beginner (3rd edition)". I am in the chapter introducing custom modules and I believe this may be an error in the coding in the book, because I have checked it 5 or 6 times and matched it exactly.
First we have a custom module games.py
class Player(object):
""" A player for a game. """
def __init__(self, name, score = 0):
self.name = name
self.score = score
def __str__(self):
rep = self.name + ":\t" + str(self.score)
return rep
def ask_yes_no(question):
""" Ask a yes or no question. """
response = None
while response not in ("y", "n"):
response = input(question).lower()
return response
def ask_number(question, low, high):
""" Ask for a number within a range """
response = None
while response not in range (low, high):
response = int(input(question))
return response
if __name__ == "__main__":
print("You ran this module directly (and did not 'import' it).")
input("\n\nPress the enter key to exit.")
And now the SimpleGame.py
import games, random
print("Welcome to the world's simplest game!\n")
again = None
while again != "n":
players = []
num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5)
for i in range(num):
name = input("Player name: ")
score = random.randrange(100) + 1
player = games.Player(name, score)
players.append(player)
print("\nHere are the game results:")
for player in players:
print(player)
again = games.ask_yes_no("\nDo you want to play again? (y/n): ")
input("\n\nPress the enter key to exit.")
So this is exactly how the code appears in the book. When I run the program I get the error IndentationError at for i in range(num):. I expected this would happen so I changed it and removed 1 tab or 4 spaces in front of each line from for i in range(num) to again = games.ask_yes_no("\nDo you want to play again? (y/n): ").
After this the output is "Welcome to the world's simplest game!" and that's it.
I was wondering if someone could let me know why this is happening?
Also, the import games module, is recognized in Eclipse after I added the path to PYTHONPATH.
I actually have this book myself. And yes, it is a typo. Here is how to fix it:
# SimpleGame.py
import games, random
print("Welcome to the world's simplest game!\n")
again = None
while again != "n":
players = []
num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5)
for i in range(num):
name = input("Player name: ")
score = random.randrange(100) + 1
player = games.Player(name, score)
players.append(player)
print("\nHere are the game results:")
for player in players:
print(player)
again = games.ask_yes_no("\nDo you want to play again? (y/n): ")
input("\n\nPress the enter key to exit.")
All I did was indent num 4 spaces and lined it up with the first for-loop.
You have an infinite loop here:
again = None
while again != "n":
players = []
If this is exactly the way it's printed in the book, the book does have an error.
You've got these two lines:
num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5)
for i in range(num):
The second one is more indented than the first. That's only legal if the first one is a block-introducer like a for or while or if. Since it's not, this is an IndentationError. And that's exactly what Python is telling you.
(It's possible that you've copied things wrong. It's also possible that you're mixing tabs and spaces, so it actually looks right in your editor, but it looks wrong to Python. But if neither of those is true, the book is wrong.)
So, you attempted to fix it by dedenting everything from that for loop on.
But when you do that, only one line is still left under the while loop:
while again != "n":
players = []
There's nothing that can possibly change again to "n", so this will just spin forever, doing nothing, and not moving on to the rest of the program.
So, what you probably want to do is to indent the num = … line to the same level as the for i… line, so both of them (and all the stuff after) ends up inside the while loop.