Soooo, this is killing me right now. Should've asked a lot earlier, but there we go. So I think there is something wrong with the zip that I've made, and it's driving me mad. If there's an another way to do this, please let me konw, but if you teach me how to use zip, that'll be great to. Also if someone can point out all the things I've messed up, that would be fantastic.
fun_string = """In ___0___, crazy ___1___ with ___2___, ate a meal called ___3___ on a grill""",
horror_string = """In ___0___ owned by ___1___, many were killed by ___2___ because of huanted ___3___""",
mystery_string = """The most mysterious place on Earth is ___0___, next to ___1___'s house because of a ___2___ living in ___3___"""
answers = [ ]
blanks = ["___0___", "___1___", "___2___", "___3___"]
def select_level():
user_input = raw_input("""Type in a story you wish to play: """)
while user_input not in ["Fun","Horror","Mystery"]:
user_input = raw_input("Invalid story. Please try again: ")
if user_input == "Fun":
quiz(fun_string, answers, blanks)
if user_input == "Horror":
quiz(horror_string, answers, blanks)
if user_input == "Mystery":
quiz(mystery_string, answers, blanks)
def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
iterables = map(iter, iterables)
while iterables:
yield tuple(map(next, iterables))
def quiz(quiz_string, answers, blanks):
print quiz_string
for answer, question in zip(answers, blanks):
raw_input ("Type in a word: ")
quiz_string = quiz_string.replace(blanks[1], answers)
if blanks == None:
print quiz_string
print """Welcome to kis ReMadlibs!!!!"""
print """Select a story you wish to particiate!!"""
print """Fun, Horror, Mystery"""
print select_level()
It's not clear why you're using your own zip() instead of Python's zip(), nor why you believe you need zip() at all. You can get this program to work by simplifying the code:
fun_string = """In ___0___, crazy ___1___ with ___2___, ate a meal called ___3___ on a grill"""
horror_string = """In ___0___ owned by ___1___, many were killed by ___2___ because of huanted ___3___"""
mystery_string = """The most mysterious place on Earth is ___0___, next to ___1___'s house because of a ___2___ living in ___3___"""
answers = []
blanks = ["___0___", "___1___", "___2___", "___3___"]
def select_level():
user_input = raw_input("Type in a story you wish to play: ")
while user_input not in ["Fun", "Horror", "Mystery"]:
user_input = raw_input("Invalid story. Please try again: ")
if user_input == "Fun":
quiz(fun_string, answers, blanks)
elif user_input == "Horror":
quiz(horror_string, answers, blanks)
elif user_input == "Mystery":
quiz(mystery_string, answers, blanks)
def quiz(quiz_string, answers, blanks):
print quiz_string
for blank in blanks:
answer = raw_input("Type in a word: ")
quiz_string = quiz_string.replace(blank, answer)
answers.append(answer)
print quiz_string
print """Welcome to kis ReMadlibs!!!!"""
print """Select a story you wish to particiate!!"""
print """Fun, Horror, Mystery"""
select_level()
Related
I'm writing a code that allows a user to enter a city they have been to. After the user inputs it, I want my code to return a randomly generated remark about the city from my list. However, whenever I run the code, it concatenates the user input with a random letter, which is not my intention of the code.
import random
message = "Type your city here: "
#Comments to concatenate with user input
comments = [f"what a lovely {}", f"I always wanted to visit {}", "I hope you enjoyed your trip to {}"]
#While loop for user input
while True:
message = input(message)
for elem in comments:
message += random.choice(elem)
if message == "quit":
break
I assume this is what your looking for?
import random
#Comments to concatenate with user input
comments = ["what a lovely ", "I always wanted to visit ", "I hope you enjoyed your trip to "]
#While loop for user input
message = None
while message != "quit":
message = input("Type your city here: ")
print(random.choice(comments)+message)
I recommend coding a function that takes the city as input then at the end returns the list. Like this
def random_quote(city):
comments = [f"what a lovely ", f"I always wanted to visit ", "I hope you
enjoyed your trip to "]
comment = random.choice(comments)
return comment + city
random.choice() accepts a list (take a look at the docs), Don't iterate over your comments variable, pass it to random.choice() and don't forget to replace {} with the city:
city = input('Please enter a city')
comment = random.choice(comments)
comment.replace('{}', city)
print(comment)
You do not need a for loop inside your while. You should always avoid while True as it is an opening for bugs. Having a break inside a loop usually marks bad programming.
You should probably read a bit about what f-string is before using it, you also don't seem to know what random.choice does since you put it into the for which gave it the messages, which it randomly took a character out of.
import random
def main():
prompt = "Type your city here: "
# Comments to concatenate with user input
comments = ["what a lovely ", "I always wanted to visit ", "I hope you enjoyed your trip to "]
usr_input = input(prompt)
# While loop for user input
while usr_input != 'quit':
message = random.choice(comments) + usr_input
usr_input = input(prompt)
if __name__ == '__main__':
main()
So I'm designing a sign-in AI, and I want it to work so that the admin name is Shawn. Here is my issue:
The program starts with the interface -
def interface():
username = input('Hello traveler, what is your name? ')
lowerUsername = username.lower()
print()
print()
if lowerUsername == 'megan':
print()
print('So you are the one Shawn has told me so much about? You are looking beautiful today my dear βΊοΈπ·')
elif lowerUsername == 'shawn':
OfficialSignInEdit()
So you can see at the end that if the user inputs that their name is 'shawn' at sign-in, it calls on the OfficialSignInEdit function, which is the admin sign in. It looks like this:
def OfficialSignInEdit():
print()
if PossInputs('perio', 'What street did you grow up on?: ') == correct:
print()
print('Greetings Master Shawn, it is a pleasure to see you again π')
else:
print()
res1 = input('Incorrect password, try again? (Yes/No)')
lowres1 = res1.lower()
if lowres1 == 'yes':
print()
print()
OfficialSignIn()
elif lowres1 == 'no':
print()
print()
interface()
So I have pinpointed the source of my issue to be right here in this particular line:
if PossInputs('perio', 'What street did you grow up on?: ') == correct:
print()
print('Greetings Master Shawn, it is a pleasure to see you again π')
this (just for your reference) is the PossInputs function:
def PossInputs(x, y):
term = x
question = input(y)
lowQuestion = question.lower()
words = lowQuestion.split()
if term in words:
print()
print (correct)
else:
print()
print (incorrect)
So what I want to happen is, when 'shawn' is entered as a name, the program will jump to the OfficialSignInEdit Function, and ask the question 'What street did you grow up on?'. Then IF the user enters the answer 'perio', the program will print 'correct', and then print the message 'Greetings Master Shawn, it is a pleasure to see you again'. I tried to say that IF PossInputs == correct (and I did define correct = 'correct', and incorrect = 'incorrect' outside all functions) then this would happen, but instead it prints 'correct', and then 'Incorrect password, try again? (Yes/No)', so how can I make a conditional statement that says that if the user answers 'perio', then it will print the welcome message?
Just for thoroughness sake, I also tried
if PossInputs('perio', 'What street did you grow up on?: ') == True
also without success...
anyways anything you can give me is extremely appreciated, if you have any questions or you would like to to clarify something about the written code, I would be more than happy to get back with you as soon as I can.
Thanks!
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 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.
Creating function to print question, add choices to a list.
def print_et_list ():
answer_list = []
function = open ("modStory.txt","r")
#Question
question = function.readline()
print question
#Choices
one = answer_list.append (function.readline())
two = answer_list.append (function.readline())
for item in answer_list:
print item
#Solution
try:
solution = int(function.readline())
except:
print "There's an error in the answer"
##for the blank line
function.readline()
return question, one, two, solution, function
##Function for prompting the user for an answer, comparing an answer, keeping score and printing score.
def hey_user (solution):
score = 0
user_answer = int(raw_input ("Enter what you think the answer is, user.\n"))
if user_answer == solution:
print "You've got it right!"
score = score + 1
elif user_answer == 0:
sys.exit()
else:
print "You've got it wrong."
return score
def main ():
question, one, two, solution, function = print_et_list()
scoresofar = hey_user (solution)
print "\nYour score is now", scoresofar
while question:
question, one, two, solution, function = print_et_list()
function.close()
main ()
raw_input ("Hit enter to exit.")
For some reason I am unable to get this thing to loop properly. The code above infinte loops itself.
This following is the text file in question which is just garbled song lyrics. The program will run the first fragment properly, and will infinte loop the first fragment once the user gives the answer.
Can you carry my drink I have everything else
1 - I can tie my tie all by myself
2 - I'm getting tired, I'm forgetting why
2
is diving diving diving diving off the balcony
1 - Tired and wired we ruin too easy
2 - sleep in our clothes and wait for winter to leave
1
While it sings to itself or whatever it does
1 - when it sings to itself of its long lost loves
2 - I'm getting tired, I'm forgetting why
2
To correct the infinite loop, avoid to re-open the file on each call to print_et_list()
Try this (I renamed function into file_handle to be a little more explicit while reading the code)
import sys
def print_et_list (file_handle):
answer_list = []
#Question
question = file_handle.readline()
print question
#Choices
one = file_handle.readline()
two = file_handle.readline()
answer_list.append(one)
answer_list.append (two)
for item in answer_list:
print item
#Solution
solution = None
try:
result = file_handle.readline()
result.replace("\n","")
solution = int(result)
except:
print "There's an error in the answer"
##for the blank line
file_handle.readline()
return question, one, two, solution
##file_handle for prompting the user for an answer, comparing an answer, keeping score and printing score.
def hey_user (solution, score=0):
user_answer = int(raw_input ("Enter what you think the answer is, user.\n"))
print "you answered '%s'"%user_answer
if user_answer == solution:
print "You've got it right!"
score += 1
elif user_answer == 0:
sys.exit()
else:
print "You've got it wrong."
return score
def main ():
file_handle = open ("modStory.txt","r")
question, one, two, solution = print_et_list(file_handle)
scoresofar = hey_user(solution)
print "\nYour score is now", scoresofar
while question:
question, one, two, solution = print_et_list(file_handle)
if question:
scoresofar = hey_user(solution, scoresofar)
print "\nYour score is now", scoresofar
file_handle.close()
main ()
raw_input ("Hit enter to exit.")
This is not a perfect version, but it seems to work ;)
append doesn't return anything, so one and two are None.