So when I run this on sublime ctrl-b I get the following output:
2
this is a example string with a _x_
ok so you have 3 left
What is your guess?
However when I run this in git-bash it simply runs, no errors, no output, no request for user input. I am new at this, and this is just a small part of a school quiz I am doing. Any suggestions?
string1 = "this is a example string with a _x_"
sample_list = [1, 2, 3]
def main():
print (sample_list[1])
print (string1)
chances = 3
while chances > 0:
print ("ok so you have " + str(chances) + " left")
answer = input("What is your guess?")
if answer == sample_list[0]:
print ("Great, here is your new string!")
print (string1.replace('_x_', str(sample_list[1])))
elif answer != sample_list[1]:
print ("Aw Schucks")
chances -= 1
print ("Out of chances")
main()
Related
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.
While working on my program I have run into a problem where the information stored in Menu option 1 is not being transferred to Menu option 2. As you can see it is correctly stored when in menu one. When it returns to go to menu option 2 its like it never went to option 1.
update #1:
some suggestions I've had is to understand scope? from what I can tell the program is not passing the data along to its parent program even though I've typed out return in each of the definitions.
#Must be able to store at least 4 grades
#Each class can have up to 6 tests and 8 hw's
#Weighted 40%*testavg 40% hw average attendance is 20%
#User must be able to input a minimum grade warning
#after each test the your program must calculate the students average and issue warning if necessary
##Define the Modules##
import math
def menu (a): #2nd thing to happen
menuend = 'a'
while menuend not in 'e':
menuend = raw_input("Type anything other then 'e' to continue:\n")
print "What would you like to do ?"
menudo = 0
print "1 - Enter Courses\n2 - Select Course to Edit\n3 - Save File\n4 - Load File\n5 - Exit\n"
menudo = input("Enter Selection:")
if (menudo == 1):
menuchck = 0
menuchck = raw_input("\nYou have entered #1 (y/n)?:\n")
if menuchck in ["Yes","yes","y","Y"]:
x = m1()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 2):
menuchck1 = 0
menuchck1 = raw_input("\nYou have entered #2 (y/n)?:\n")
if menuchck1 in ["Yes","yes","y","Y"]:
x = m2()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 3):
print "Entered 3"
elif (menudo == 4):
print "Entered 4"
else:
print "Anything Else Entered"
def course(): #3rd thing to happen
b = {}
while True:
while True:
print "\n",name,", please enter your courses below ('e' to end):"
coursename = raw_input("Course Name:")
if (coursename == 'e'):
break
will = None
while will not in ('y','n'):
will = raw_input('Ok for this name : %s ? (y/n)' % coursename)
if will=='y':
b[coursename] = {}
print "\n",name,", current course load:\n",b
coursechck = None
while coursechck not in ('y','n'):
coursechck = raw_input("Are your courses correct (y/n)")
if coursechck =='y':
return b
else:
b = {}
print
##Menu Options##
def m1():
a = course()
return a
def m2():
print "Excellent",name,"lets see what courses your enrolled in\n"
print x
return x
###User Input Section###
name = raw_input("Enter Students Name:\n")
a = {}
menu(a)
raw_input("This is the end, my only friend the end")
In your if-elif blocks in the do==1 case, you write m1(), but for the last case, you write x=m1(). You should have the latter everywhere (by typing m1() you only run the function, but do not store the returned x anywhere).
By the way, you can avoid this if-elif confusion using if chck in ["Yes","yes","Y","y"]:
I'm new to programming, and I tried to make a python program. Here it is:
import time
gravity = 0
space = 0
print "Welcome to the 'Find out who is in space' program"
person_messy = raw_input("Enter a name:")
person = person_messy.lower()
if len(person) < 5:
print "Make sure you put the first AND last name"
else:
space = 1
print "Searching database....."
if person == "oleg kotov" or "mike hopkins" or "sergey ryazanskiy" or "fyodor yurchikhin" or "karen nyberg" or "luca permitano":
gravity = 1
else:
gravity = 0
time.sleep(1)
if space == 1:
print "loading..."
time.sleep(1)
if space == 1:
print "loading..."
time.sleep(1)
if space == 1:
print "loading..."
if gravity == 1:
print person + "is in space!"
else:
print "You and " + person + "are on the same planet."
this is the error I got:
Internal error: ReferenceError: _select is not defined
I had the same problem on similar code... You can't use time.sleep or it gives this. I don't know why, but that fixed my code(not using time.sleep)
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.