I have recently made a quiz in my computer science lesson but for some reason it did not work, I am new to programming and I was wondering maybe you could help me, I know that it will be something simple but as I said, I am new to this. I have only copied 4 questions out of the 8 I have made but for some reason it ignores the IF statement and goes straight to the else statement. The code is the following:
score=0
print("Welcome the the general knowledge quiz")
your_name = input("What is your name?: ")
input("Press Enter to Start the Quiz!")
print("1) Who presents Pointless?")
answer = input()
if answer == ["Alexander Armstong", "alexander armstrong", "ALEXANDER
ARMSTRONG"]:
print("Well done", your_name)
score = score+1
else:
print("Sorry, the answer was Alexander Armstrong")
print("Your score is", score)
print("2) Who presents I'm a celeb, get me out of here?")
answer = input()
if answer == ["Ant and Dec", "ant and dec", "ANT AND DEC", "Ant And Dec"]:
print("Well done", your_name)
score = score+1
else:
print("Sorry, the answer was Ant and Dec")
print("Your score is", score)
print("3) What is the capital of England?")
answer = input()
if answer == ["London", "london", "LONDON"]:
print("Well done", your_name)
score = score+1
else:
print("Sorry, the answer was London")
print("Your score is", score)
print("4) Who lives on the White house right now?")
answer = input()
if answer == ["Obama", "obama", "Barack Obama", "barack obama"]:
print("Well done", your_name)
score = score+1
else:
print("Sorry, the answer was Barack Obama")
print("Your score is", score)
answer = input()
if answer == ["Alexander Armstong", "alexander armstrong", "ALEXANDER
ARMSTRONG ):
Missing quotation mark aside, this if statement will always fail. input() always returns a string, but you're checking if it's equal to a list, which can never be true. If you replace == with in, it will do what you expect.
Also, you should consider using .lower() to make the answer into lowercase, then you'd only have one value to check.
There's a hint in the syntax highlighting: you're missing a ":
if answer == ["Alexander Armstong", "alexander armstrong", "ALEXANDER ARMSTRONG ):
print("Well done", your_name)
There's no " after ARMSTRONG.
Related
print("Welcome to my quiz page!")
playing = input("Do you want to play? ")
if playing.lower() == "yes": #when people answer no here, the quiz should stop but it doesn't. why?
print("Let's play! ")
score = 0
answer = input("What is the capital of Japan? ")
if answer.lower() == "tokyo":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What is a female Japansese dress called? ")
if answer.lower() == "kimono":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What are Japanese gang members called? ")
if answer.lower() == "yakuza":
print("Correct!")
score += 1
else:
print("Incorrect!")
print("You've got " + str(score) + " questions correct!")
print("You've got " + str((score / 3) * 100) + "%,")
When I answer "no" it still let me carry on playing the quiz instead of quitting. How can I stop it running when people answer no instead of yes?
The quiz does not stop because you have not included any code to stop the quiz when the user enters "no". To fix this, you can add an else statement after the if statement that checks if the user wants to play. The else statement should contain a break statement to exit the loop.
Here How you can do so:
print("Welcome to my quiz page!")
while True:
playing = input("Do you want to play? ")
if playing.lower() == "yes" or playing.lower() == "y":
print("Let's play! ")
score = 0
answer = input("What is the capital of Japan? ")
if answer.lower() == "tokyo":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What is a female Japansese dress called? ")
if answer.lower() == "kimono":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What are Japanese gang members called? ")
if answer.lower() == "yakuza":
print("Correct!")
score += 1
else:
print("Incorrect!")
print("You've got " + str(score) + " questions correct!")
print("You've got " + str((score / 3) * 100) + "%,")
else:
break
You can make this more manageable by constructing a list of questions and answers rather than writing discrete blocks of code for each.
You need to be asking the user if they want to answer questions (or not).
So...
Q_and_A = [
('What is the capital of Japan', 'Tokyo'),
('What is a female Japansese dress called', 'kimono'),
('What are Japanese gang members called', 'yakuza')
]
score = 0
for q, a in Q_and_A:
if input('Would you like to try to answer a question? ').lower() in {'n', 'no'}:
break
if input(f'{q}? ').lower() == a.lower():
print('Correct')
score += 1
else:
print('Incorrect')
print(f'Your total score is {score} out of a possible {len(Q_and_A)}')
Thus if you want to add more questions and answers you just change the list of tuples. The rest of the code doesn't need to be changed
I am new to coding. It works alright until you guess a number. then it says either higher or lower eternally. Please help me understand what I've done wrong. I have tried searching the internet and trying to retype some of the code but it won't work. I am trying to make a conversation as well as a mini guess the number game.
Here's my Code
# Conversation A
import random
print("Answer all questions with 'yes' or 'no' and press ENTER")
print('Hello I am Jim the computer')
z = input('How are you? ')
if z == 'Good' or z == 'Great' or z == 'good' or z == 'great':
print("That's great!")
else:
print("Oh. That's sad. I hope you feel better.")
a = input("what's your name? ")
print(a + "? Thats a nice name.")
b = input('Do you own any pets? ')
if b == 'yes' or b == 'Yes':
print("That's cool. I love pets!")
else:
print("That's a shame, you should get a pet. ")
c = input("Do you like animals? ")
if c == 'yes' or c == 'Yes':
print("Great! Me too!")
else:
print("Oh that's sad. They're really cute. ")
d = input("Do you want to see a magic trick? ")
if d == "yes" or d == "Yes":
input("Ok! Think of a number between 1-30. Do you have it? ")
print("Double that number.")
print("Add ten.")
print("Now divide by 2...")
print("And subtract your original number!")
y = input("Was your answer 5? ")
if y == 'yes' or y == 'Yes':
print("Yay i got it right! I hope you like my magic trick.")
else:
print("Oh that's sad. I'll work on it. I really like magic tricks and games.")
else:
print("Ok. Maybe next time. I love magic tricks and games!")
e = input("Do you want to play a game with me? ")
if e == "yes" or e == "Yes":
randnum = random.randint(1,100)
print("I am thinking of a number between 1 and 100...")
if e == 'no' or e == 'No':
print("oh well see you next time" + a + '.')
guess = int(input())
while guess is not randnum:
if guess == randnum:
print("Nice guess " + a + "! Bye, have a nice day!")
if guess < randnum:
print("Higher.")
if guess > randnum:
print("Lower.")
You need to add a break statement when you want stop looping and move the input for guess inside the loop so you don't exit before printing the statement:
while True:
guess = int(input())
if guess == randnum:
print("Nice guess " + a + "! Bye, have a nice day!")
break
Edit: Also, you dont want to use is every time: Is there a difference between "==" and "is"?
So, if the person answers "nutella", it prints "That's correct!" How do I get it to say "You're wrong!" if they answer anything else.
nutella = input
input("What's the best food in the world?")
if nutella:
print("That's correct!")
else:
print("You're wrong!")
Firstly, it seems you should look into if statements since you don't know how to use them yet, but this is how you do it, I'll try to explain as well
choice = input("What's the best food in the world?")
if choice == "Nutella":
print("That's correct!")
else:
print("You're wrong!")
So the first line assigns what the person types to the variable choice and then in the next line it checks if the value of the variable equals/is "nutella", if it is it will print "That's correct!", if it isn't it will print "You're wrong!".
The if statement in Python for a string is true whenever the string isn't empty. What you want is to compare the nutella variable with the expected string. Such as:
nutella = input("What's the best food in the world?")
if nutella == "nutella":
print("That's correct!")
else:
print("You're wrong!")
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)
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 >>")