Sorry for the horrible question. Basically, I am making the Yes or No game in Python and I need it to print something e.g. "You Win" if they input something from a library that I have already made with every acceptable word. TY in advance
q1 = input ("Answer: ")
while q1 == "yes" or "Yes" or "no" or "No":
print ("Sorry but you answered \"" + q1 + "\" which means you lose!")
sys.exit ("\nGame Over")
if q1 == ###:
print ("Well done you have earned yourself a point")
score +=1
print ("Your current score is: " + score)
input_word = input('Insert a word: ')
list_of_acceptable_words = ['word1', 'word2']
if input_word in list_of_acceptable_words:
print('You Win')
Where input_word is a string containing the input from the user and list_of_acceptable_words is a list of acceptable words
You can probably start out from this snippet, using the built-in set type:
>>> lib={'Alice','Bob'}
>>> print('Bob' in lib)
True
>>> print('Carol' in lib)
False
Then one can add a bit of code around to match your needs more closely:
>>> guess='Dave'
>>> print(['You lose...', 'You WIN!'][guess in lib])
You lose...
>>> guess='Alice'
>>> print(['You lose...', 'You WIN!'][guess in lib])
You WIN!
Edit: now that you have updated your OP with some snippet, I can write some code more in line with your needs.
accepted=set(line.strip() for line in open('accepted.txt'))
q1 = input("Answer: ")
while q1.lower() in {"yes", "no"}:
print ("Sorry but you answered \"" + q1 + "\" which means you lose!")
sys.exit ("\nGame Over")
if q1 in accepted:
print ("Well done you have earned yourself a point")
score +=1
print ("Your current score is: " + score)
Of course, if you count good answers, you will want to put this into some loop, then the initializition of accepted can stay outside.
Related
When you enter the correct answer ("Bad Guy"), it prints score = 3 and score = 1 at the same time? How do I prevent this so after getting it right in one attempt, it displays (and saves) score = 3, and after getting it right on the second attempt, it displays (and saves) the score as 1? By the way, if the player guesses correctly the first time, they gain 3 points.If they get it wrong, they try again. If they guess correctly the second time, they only gain 1 point. If they still get it wrong, the game ends. Please explain what's wrong and try to fix this problem please.
Here's the code I'm using for this:
score = 0
print("Round 1:")
with open('songs.txt') as songs_list:
song_name = songs_list.readline()
answer = input("What is the song name? " + song_name)
if answer == "Bad Guy":
score+=3
print("Correct! Score = 3")
else:
print("Incorrect! Try again.")
answer = input("What is the song name? " + song_name)
if answer == "Bad Guy":
score +=1
print("Correct! Score = 1")
else:
print("Incorrect! Unlucky, you lost. I hope you enjoyed playing!")
import sys
sys.exit()
You should indent the second set of if-else statements. This means the second set will only occur if the first answer is wrong.
score = 0
print("Round 1:")
with open('songs.txt') as songs_list:
song_name = songs_list.readline()
answer = input("What is the song name? " + song_name)
if answer == "Bad Guy":
score+=3
print("Correct! Score = 3")
else:
print("Incorrect! Try again.")
answer = input("What is the song name? " + song_name)
if answer == "Bad Guy":
score +=1
print("Correct! Score = 1")
else:
print("Incorrect! Unlucky, you lost. I hope you enjoyed playing!")
import sys
sys.exit()
Your most immediate problem is that you never print score. Your only reports to the user are the literal strings Score = 3 and Score = 1. You'll need something like
print("you got 3 more points; new score =", score)
So I have an assessment due tomorrow (it is all finished) and was hoping to add a few more details in.
How would I:
a. Make it so that if you answer the question wrong, you can retry twice
b. if you completely fail, you get shown the answer
How would i do this? thanks
ps. The code lloks retarded, i couldn't get it in
} output = " " score = 0 print('Hello, and welcome to my quiz on Ed Sheeran!') for question_number,question in enumerate(questions): print ("Question",question_number+1)
print (question)
for options in questions[question][:-1]:
print (options)
user_choice = input("Make your choice : ")
if user_choice == questions[question][-1]:
print ("Correct!")
score += 1
print (score)
print (output)
else:
print ("Wrong!")
print (score)
print (output)
print(score)
What I have understood from your query is that you want user to input the option twice before we move to the next question.
Also you want to display the answer if the user has incorrectly answered in both the chances.
I don't know how your questions and answers are stored but you can use the below code as a pseudo code.
The below code should work:
print('Hello, and welcome to my quiz on Ed Sheeran!')
for question_number,question in enumerate(questions):
print ("Question",question_number+1)
print (question)
tmp = 0
for options in questions[question][:-1]:
print (options)
for j in range(2):
user_choice = input("Make your choice : ")
if user_choice == questions[question][-1]:
print ("Correct!")
score += 1
break
else:
print ("Wrong!")
tmp += 1
if tmp == 2:
print ('You got it wrong, Correct answer is: ' output)
print(score)
I'm trying to get a string to keep repeating if the answer is wrong. How would I go about doing this? The code I have is below which works but doesn't repeat the answer.
print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = input()
if answer is '4':
print("Great job!")
elif answer != '4':
print ("Nope! please try again.")
while answer != '4':
print ("What is 2 + 2?")
break
There are a couple of things wrong with your code. Firstly, you are only asking for the answer once at the moment. You need to put answer = input() in a while loop. Secondly, you need to use == instead of is:
print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = 0
while answer != '4':
answer = input()
if answer == '4':
print("Great job!")
else:
print ("Nope! please try again.")
There are a number of ways you can arrange this code. This is just one of them
print('Guess 2 + 2: ')
answer = int(input())
while answer != 4:
print('try again')
answer = int(input())
print('congrats!')
I think this is the simplest solution.
By now you've got more answers than you can handle, but here are another couple of subtleties, with notes:
while True: # loop indefinitely until we hit a break...
answer = input('What is 2 + 2 ? ') # ...which allows this line of code to be written just once (the DRY principle of programming: Don't Repeat Yourself)
try:
answer = float(answer) # let's convert to float rather than int so that both '4' and '4.0' are valid answers
except: # we hit this if the user entered some garbage that cannot be interpreted as a number...
pass # ...but don't worry: answer will remain as a string, so it will fail the test on the next line and be considered wrong like anything else
if answer == 4.0:
print("Correct!")
break # this is the only way out of the loop
print("Wrong! Try again...")
You only need the wrong-answer check as loop condition and then output the "great job" message when the loop is over (no if is needed):
print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = input()
while answer != '4':
print ("Nope! please try again.")
print ("What is 2 + 2?")
answer = input()
print("Great job!")
Here is my two cents for python2 :
#!/usr/bin/env python
MyName = raw_input("Hello there, what is your name ? ")
print("Nice to meet you " + MyName)
answer = raw_input('What is 2 + 2 ? ')
while answer != '4':
print("Nope ! Please try again")
answer = raw_input('What is 2 + 2 ? ')
print("Great job !")
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 have this problem when i run the program it all goes good an all, but when a user gets the right answer, the code does not print neither print("Good Job!") or print("Correct"). what is wrong with the code ?
import random
firstNumber = random.randint(1, 50)
secondNumber = random.randint(1, 50)
result = firstNumber + secondNumber
result = int(result)
print("Hello ! What\'s your name ? ")
name = input()
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
userAnswer = int(input("Your answer : "))
while (userAnswer != result) :
if (userAnswer > result) :
print("Wrong")
else:
print("Wrong")
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
input("\n\n Press to exit")
The problem is that your while-loop will only run as long as the first answer is wrong. Everything that is indented after while (userAnswer != result) will be ignored by Python if the first answer is right. So logically a first correct answer can never reach print("Correct"), since that would require the answer to be both wrong (to start the while loop) and right (to get to "Correct").
One option is to get rid of the while-loop, and just use if's. You get two chances this way, then you lose.
if (userAnswer == result):
print("Well done!")
else:
print("Wrong")
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
else:
print("Nope all wrong you lose")
Another option is to make an infinite loop using While. (like #csharpcoder said)
while (True) :
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print ("Wrong answer")
In the last option a wrong answer gets "Wrong answer" and the while-loop starts again, since True is of course still True. So you try again, until you get the right answer, which will bring you to "correct, good job" and then break (which stops the loop).
I struggled with while-loops and kind of getting it in my head that indentation means Python will treat it as 'one thing' and skip it all if I start it with something that's False.
If the answer is correct, then
while (userAnswer != result) :
will cause the loop contents to be skipped.
First of all, you get input outside of your loop and then don't do anything with it. If your answer is correct on the first try, you will get no output because userAnswer != result will be False immediately and your while loop won't run.
Some other points:
if (userAnswer > result) :
print("Wrong")
else:
print("Wrong")
is redundant because you are guaranteed to fall into one of these, as you will only get here if the answer is wrong (and therefore > or < result). Just print "Wrong" without a condition, as the only reason this would run is if the answer was wrong.
print("Correct")
print("Good Job!")
You can use \n to print on a new line instead of having multiple print statements together. Usually you only use multiple prints together for readability, but print("Correct\nGood job!") isn't that much less readable.
if (userAnswer == result):
#...
break
You don't need break here because the answer is already correct and the loop won't repeat anyway.
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
Here, you append string literals to string literals ("Hello!" + " "). You don't need to do that as you can just write "Hello! ".
result = firstNumber + secondNumber
result = int(result)
The result (pun not intended) is already an integer, so you don't need to convert it.
How about using a infinite while loop something like this :
while (True) :
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print ("Wrong answer")
In your logic if you enter the wrong answer first time and correct answer afterwards , then it will work as per your requirement , but if you enter the correct answer first time it will simple skip the while loop .
I played around a bit to refactor, in an attempt to make it more clear:
import random
name = input("Hello ! What's your name? ")
print("Hello, {name}!".format(name=name))
print("Ok, {name}, let's start!".format(name=name))
first_number = random.randint(1, 50)
second_number = random.randint(1, 50)
correct_answer = first_number + second_number
print("What is, '{first} + {second}'?".format(first=first_number,
second=second_number))
user_answer = None
while user_answer != correct_answer:
try:
user_answer = int(input("Your answer : ")) # ValueError will be raised if non integer value given
except ValueError:
print("Invalid Input!")
user_answer = None
if user_answer:
if user_answer == correct_answer:
print("Correct")
print("Good Job!")
else:
print('--> Wrong, try again!')
input("\n<< Press any key to exit >>")