I need help with writing my program in Python 2.7.
My problem is that I am not sure how to start the program again if the user inputs 'yes'. Here is my program:
import random
#Set up the lists for charades and the answers (words)
charadelist = ["Mary's father has 5 daughters: Chacha, Chichi, Cheche, Chocho. What is the name of the 5th daughter?"]
wordlist = ["Mary"]
lencharades = len(charadelist)
lenwords = len(wordlist)
rndnum = random.randrange (0, lenwords)
answer = wordlist[rndnum]
charade = charadelist[rndnum]
print "***Welcome to Charades!***"
print "You are given a charade. Try to guess the answer:"
print '"'+charade+'"'
guess = raw_input('Your answer: ')
if guess == answer:
print "Well done!"
else:
print "Sorry, the correct answer is " + '"'+answer+'"' + '.'
print 'Do you want to play again?'
reply = raw_input('Type `yes` or `no`: ')
if reply == 'yes':
# How do I run the program again??? Please help
if reply == 'no':
print 'Thanks for playing!'
exit
Thanks.
I would recommend running your game inside a function, that way you can call it any time:
import random
def runGame():
#Set up the lists for charades and the answers (words)
charadelist = ["Mary's father has 5 daughters: Chacha, Chichi, Cheche, Chocho. What is the name of the 5th daughter?"]
wordlist = ["Mary"]
lencharades = len(charadelist)
lenwords = len(wordlist)
rndnum = random.randrange (0, lenwords)
answer = wordlist[rndnum]
charade = charadelist[rndnum]
print "***Welcome to Charades!***"
print "You are given a charade. Try to guess the answer:"
print '"'+charade+'"'
guess = raw_input('Your answer: ')
if guess == answer:
print "Well done!"
else:
print "Sorry, the correct answer is " + '"'+answer+'"' + '.'
reply = ""
while reply != 'no':
runGame()
print 'Do you want to play again?'
reply = raw_input('Type `yes` or `no`: ')
if reply == 'no':
print 'Thanks for playing!'
Try this:
import random
#Set up the lists for charades and the answers (words)
charadelist = ["Mary's father has 5 daughters: Chacha, Chichi, Cheche, Chocho. What is the name of the 5th daughter?"]
wordlist = ["Mary"]
lencharades = len(charadelist)
lenwords = len(wordlist)
rndnum = random.randrange (0, lenwords)
answer = wordlist[rndnum]
charade = charadelist[rndnum]
print "***Welcome to Charades!***"
print "You are given a charade. Try to guess the answer:"
rep = "yes"
while rep == "yes":
print '"'+charade+'"'
guess = raw_input('Your answer: ')
if guess == answer:
print "Well done!"
else:
print "Sorry, the correct answer is " + '"'+answer+'"' + '.'
print 'Do you want to play again?'
reply = raw_input('Type `yes` or `no`: ')
if reply == 'yes':
pass
# How do I run the program again??? Please help
if reply == 'no':
print 'Thanks for playing!'
rep = "no"
Maybe you can put your program in a loop.If the input is "no",break out the loop.
while(1):
your code
if reply == "no":
break
Related
I'm expanding upon the random number guessing game from Automate the Boring Stuff with Python and I can't figure out how to write the code for when the game asks if you want to play again.
More specifically, if the user types "yes" or "no" to wanting to play the game, the code does the appropriate thing. However, if the user types in anything else, I want it to say "Please answer yes or no" and then allow the user to enter another answer.
In this case, my code currently prints "Please answer yes or no", but then it treats the answer as "yes", so it starts the game again. I don't want it to immediately start a new game unless the user specifically types "yes". How can I do this?
Here's the code
import random
print ('Hello, what is your name?')
name = input ()
name = name.strip()
while True:
print ('Well, ' + name + ', I am thinking of a number between 1 and 20.')
secretNumber = random.randint (1, 20)
print ('DEBUG: Secret number is ' + str(secretNumber))
print ('Take a guess.')
for guessesTaken in range (1, 7):
try:
guess = int (input ())
if (guess < secretNumber and guessesTaken < 6):
print ('Your guess is too low. Guess again.')
elif (guess > secretNumber and guessesTaken < 6):
print ('Your guess is too high. Guess again.')
else:
break # This condition is for the correct guess
except ValueError:
print ('You did not enter a number.') # This condition is for if a non-integer is entered.
if (guess == secretNumber and guessesTaken == 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guess.')
elif (guess == secretNumber and guessesTaken > 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
else:
print ('Sorry. Your guesses were all wrong. The number I was thinking of was ' + str(secretNumber))
print ('Would you like to play again?')
answer = input ()
answer = answer.lower()
if answer == 'no':
print ('Ok.')
break
elif answer == 'yes':
print ('Ok, let\'s go!')
else:
print ('Please answer yes or no')
Simply have a second loop that will continue to prompt until a valid input is given.
usr_response = input('Would you like to play again: ').lower()
while usr_response not in ('yes','no'):
usr_response = input('Invalid response. Please choose yes or no: ')
if usr_response == 'no':
break
So the problem is that the code checks for valid input only once. If the 2nd input is invalid as well, no condition is checked. For the solution, You should replace:
if answer == 'no':
print ('Ok.')
break
elif answer == 'yes':
print ('Ok, let\'s go!')
else:
print ('Please answer yes or no')
with:
list1 = ['yes', 'no']
while answer not in list1:
print ('Please answer yes or no:')
answer = input()
if answer == 'no':
print ('Ok.')
break
elif answer == 'yes':
print ('Ok, let\'s go!')
I am making a small quiz and trying to learn python. The quiz takes the first answer then loops all the way to the bottom instead of asking the user the rest of the questions. It will print the first question, then ask for the answer , then it will run throught the rest of the code but it won't actually ask for the input or anything like that.
question_1 = ("ex1")
question_2 = ("ex2")
question_3 = ("ex3")
question_4 = ("ex4")
answer = input ("Please type the letter you think is correct: ")
count = 0
# answers
print (question_1)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "b" or answer == "B":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_2)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "a" or answer == "A":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_3)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "d" or answer == "D":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_4)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "c" or answer == "C":
print ("Correct")
count +=1
else:
print ("Incorrect")
You are only asking for one input and then checking that answer against every question.
You will need to add a new input for every question and then check against that input
e.g.
count = 0
print('Q1')
ans1 = input('A/B/C?')
if ans1.lower() == 'c': # Checks for it as a lowercase so no need to repeat it
print('Correct')
count += 1
else:
print('Incorrect')
print('Q2')
ans2 = input('A/B/C?')
if ans2.lower() == 'b':
print('Correct')
count += 1
else:
print('Incorrect')
You need to have the input() function after each question. An input is asked for at each input, writing it once before all the questions won't work.
By the way, you might want to use lists and a loop to get the same done with less code.
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.
I'm an amateur trying to code a simple troubleshooter in Python but I'm sure what function I need to use to stop this from happening...
enter image description here
What should I do so the code doesnt continue running if the user inputs yes?
TxtFile =open('Answers.txt')
lines=TxtFile.readlines()
import random
def askUser(question):
answer = input(question + "? ").lower()
Split = answer.split()
if any(word in Split for word in KW1):
return False
elif any(word in Split for word in KW2):
return True
else:
print("Please answer yes or no.")
askUser(question)
KW1=["didn't", "no",'nope','na'] #NO
KW2=["did","yes","yeah","ya","oui","si"] #YES
print (lines[0])
print("Nice to meet you, " + input("What is your name? "))
print("Welcome to my troubleshooter")
#This is the menu to make the user experience better
shooter=True
while shooter:
print('\n\n1.Enter troubleshooter\n2.Exit\n\n')
shooter=input('Press enter to continue: ')
if shooter==('2'):
print('Ok bye')
break
words = ('tablet', 'phone', 's7 edge')
while True:
question = input('What type of device do you have?: ').lower()
if any(word in question for word in words):
print("Ok, we can help you")
break
else:
print("Either we dont support your device or your answer is too vague")
if askUser("Have you tried charging your phone"):
print("It needs to personally examined by Apple")
else:
if askUser("Is it unresponsive"):
print (lines[0])
else:
print ("Ok")
if askUser("Are you using IOS 5.1 or lower"):
print (lines[1])
else:
if askUser("Have you tried a hard reboot"):
print (lines[2])
else:
if askUser("Is your device jailbroken"):
print (lines[3])
else:
if askUser("Do you have a iPhone 5 or later"):
print (lines[4])
else:
print(lines[5])
print ('Here is your case number, we have stored this on our system')
print (random.random())
Here is my code for reference.
Edit: Here is the problem
enter image description here
It should just end the code there but it doesnt. I'm not sure how I can fix it
I would recommend moving the following:
if askUser("Are you using IOS 5.1 or lower"):
print (lines[1])
else:
if askUser("Have you tried a hard reboot"):
print (lines[2])
else:
if askUser("Is your device jailbroken"):
print (lines[3])
else:
if askUser("Do you have a iPhone 5 or later"):
print (lines[4])
else:
print(lines[5])
print ('Here is your case number, we have stored this on our system')
print (random.random())
into the else part of:
if askUser("Is it unresponsive"):
Hope this helps.
I need help fixing the error. Here is my code:
import random
def game():
capitals={"England":"London","France":"Paris","Belgiom":"Brussels",\
"Canada":"Ottawa","China":"Beijing","Cyprus":"Nicosia",\
"Cuba":"Havana","Egypt":"Cairo","Greece":"Athens",\
"Ireland":"Dublin","Italy":"Rome","a":"A","B":"B"}
wrong=[]
right=[]
incorrect_answers = False
while len(capitals)>0:
pick = random.choice(list(capitals.keys()))
correct_answer = capitals.get(pick)
print ("What is the capital city of" + pick + "?")
answer = input("Your answer: ")
if answer.lower() == correct_answer.lower():
print ("That's Correct!\n")
del capitals[pick]
right.append(pick)
else:
print ("That's Incorrect.\n")
print ("The correct answer is" + correct_answer + "\n")
wrong.append(pick)
incorrect_answers = True
del capitals[pick]
print ("You got ",len(right), "/", len(wrong))
top = len(right)
bottom = len(wrong)
perc = float((top / bottom) * 100)
print(perc)
if incorrect_answers:
print ("Here are the ones that you may want to brush up on:\n")
for each in wrong:
print (each)
else:
print ("Perfect!")
def help():
print("do you neeeded efhdufghaf dfgjn")
while True:
input = input("what do you want to do? help or play?")
if input == "help":
help()
break
if input == "play":
print("you want to play")
game()
break
You shouldn't do this
input = input("what do you want to do? help or play?")
You are shadowing the function input with your variable. Change the name of your variable to something else.