I have just finished this code , added my final print line and now suddenly when I test it , it doesn't print out what I want it to print.
import random
name=input("Welcome to this Arithmetic quiz,please enter your name:")
score = 0
for i in range(10):
number1=random.randint(20,50)
number2=random.randint(1,20)
oper=random.choice('+-*')
correct_answer = eval(str(number1)+oper+str(number2))
answer = (int(input('What is:'+str(number1)+oper+str(number2)+'=')) == correct_answer)
if answer == correct_answer:
print('Correct!')
score +=1
else:
print('Incorrect!')
print("You got",score,"out of 10")
When I ever I give the right answer it still gives me Incorrect leading it to tell me that I got 0/10.
To match the symptoms reported I believe that your code is actually:
import random
name=input("Welcome to this Arithmetic quiz,please enter your name:")
score = 0
for i in range(10):
number1=random.randint(20,50)
number2=random.randint(1,20)
oper=random.choice('+-*')
correct_answer = eval(str(number1)+oper+str(number2))
answer = (int(input('What is:'+str(number1)+oper+str(number2)+'=')) == correct_answer)
if answer == correct_answer:
print('Correct!')
score +=1
else:
print('Incorrect!')
print("You got",score,"out of 10")
Note the indentation of the else statement is aligned with the if, not the for. Given that this line:
answer = (int(input('What is:'+str(number1)+oper+str(number2)+'=')) == correct_answer
assigns a boolean to the variable answer, not the answer that the user entered. You can do 2 things:
remove the == correct_answer part resulting in:
answer = int(input('What is:'+str(number1)+oper+str(number2)+'='))
or
change the if statement to:
if answer:
Here are the problems with your code:
You are incrementing score regardless of whether the answer is correct or not. Increase the indentation of score += 1 so that it lines up with the print that indicates a correct answer.
The else is bound to the for statement. Indent it so that it is bound to the if statement. Indent the print that follows it accordingly.
Your assignment to answer isn't just picking up the answer, but it's comparing it to the expected answer. So it will be True or False. You are then comparing that boolean value to the answer again, so of course the result if False. Change the assignment to:
answer = int(input('What is:'+str(number1)+oper+str(number2)+'='))
Probably the first two items were just posting errors, and the last one is what's preventing your code from working.
Related
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 3 years ago.
I am currently working on a blackjack game without graphics or pygame I can not seem to make an if statement with input, I took a month off of python and can't really understand the questions already answered.
Here is my code so far:
def pullCard():
print(f"You pulled a {r} of {s} the value is {v}")
print(f"The dealer pulled a {dr} of {ds} the value is {dv}")
pullCard()
Answer = input('Do you want to Hit or Stand?')
if Answer == 'Stand' or 'stand':
dealerOnly()
if Answer == 'Hit' or 'hit':
pullCard()
I have not defined dealerOnly() every time i say Hit or Stand it just comes out with the error.
Do you want to Hit or Stand?Hit
Do you want to Hit or Stand?
Traceback (most recent call last):
File "C:\Users\Brody Critchlow\Downloads\Blackjack\Blackjack.py", line 36, in <module>
dealerOnly()
NameError: name 'dealerOnly' is not defined
Even though i said Hit not Stand
your if statement is incorrect it should be
if Answer == 'Stand' or Answer == 'stand':
A cleaner approach is to make the user input string all lower case, that way you only need to check one scenario.
def pullCard():
print(f"You pulled a {r} of {s} the value is {v}")
print(f"The dealer pulled a {dr} of {ds} the value is {dv}")
pullCard()
Answer = str(input('Do you want to Hit or Stand?')).lower()
if Answer == 'stand':
dealerOnly()
elif Answer == 'hit':
pullCard()
I also used an elif statement to make it more efficient so that if the first statement is true, then it won't run the second.
You have to understand that python uses truthy and falsey values, it means, that not only True and False are true and false, also strings and lists and other values, examples:
if "":
print("wont enter, falsay value")
if("Hit"):
print("Something, truthy value")
if []:
print("wont enter, falsay value")
if [1,2,3]:
print("Something, truthy value")
your main problem, is in this two expressions:
if Answer == 'Stand' or 'stand':
if Answer == 'Hit' or 'hit':
here, you use an or, it means that if anything is truthy, the block inside the if will be executed, and 'stand' and 'hit' are not an empty str, so it will always be executed because they are both True
Also, the other problem is that you have to make the two questions, Answer == "Stand" or Answer == "stand", as I don't have the methods, I will print something just to you can see what is called:
def pullCard():
print("You pulled a {r} of {s} the value is {v}")
print("The dealer pulled a {dr} of {ds} the value is {dv}")
pullCard()
Answer = input('Do you want to Hit or Stand?')
if Answer == 'Stand' or Answer == 'stand':
print("dealerOnly()")
if Answer == 'Hit' or Answer == 'hit':
print("pullCard()")
you can also simplify the if like this:
Answer = input('Do you want to Hit or Stand?').lower()
if Answer == 'stand':
print("dealerOnly()")
if Answer == 'hit':
print("pullCard()")
learner in the Python (with version 2.7.5).
Currently I am working on a simple quiz script that allows the user to re-answer a question, and limit the number of chances the user can answer a question incorrectly.
So a total limit of 5 is set and a message (e.g. "END!") would be displayed to the user when the limit is reached. The limit is shared across all questions.
When I was testing the below-mentioned script, I found several problems.
1) Even the question 1 is wrongly answered for 5 times, question 2 would still be displayed, how could I prevent the next question from appearing if the limit was already reached?
2) I would like to ask where should I insert the code for the end message ("END!") if the limit was reached?
Thanks a lot!
def quiz():
score = 0
counter = 0
print "Please answer the following questions:"
print "Question 1 - ?"
print "a."
print "b."
print "c."
while counter <5:
answer = raw_input("Make your choice:")
if answer == "c":
print("Correct!")
score = score +1
else:
print("Incorrect!")
counter = counter +1
print "Question 2 - ?"
print "a."
print "b."
print "c."
while counter <5:
answer2 = raw_input("Make your choice:")
if answer2 == "a":
print("Correct!")
score = score +1
else:
print("Incorrect!")
counter = counter +1
print
print ("Your score is ") + str(score)
p.s. the code seems a bit off-placed with the copy and paste function. Sorry for causing the inconvenience
You should really refactor this to make it a little less repetitious. So I'd put the question and answer logic into their own function and pass in the question text and correct answer. However, using your code as-is, every time you increment the counter, you need to check if it's > 5 and just use while True for the loop. So for each question:
correct = "a"
while True:
answer = raw_input("Make your choice:")
if answer == correct:
print("Correct!")
score = score +1
break
else:
print("Incorrect!")
counter = counter +1
if counter == 5:
print "END!"
return
break
You are always printing the second question without checking if the limit of wrong answers has been reached. Before printing the second question you could do something like
if counter >= 5:
print "END!"
return
The return statement inside the conditional would terminate the quiz function if the limit has been reached. This needs to be done before printing any question.
Also, you could improve your code using a list of questions with answers and a simple for loop to iterate over all the questions and avoid repeating the same logic every time.
In my program it's supposed to ask the user a question and give them 3 chances to guess the correct answer. But my "while" loop seems to give the user a 4th chance to answer the question and bypassing the "max_attempts" variable.
print('Quiz program!\n')
answer = input('What is the capital of Wisconsin? ')
attempt = 1
max_attempts = 4
while answer != 'Madison':
attempt += 1
print('You got it wrong, please try again.\n')
answer = input('What is the capital of Wisconsin? ')
if attempt == max_attempts:
print('You used the maximum number of attempts, sorry. The correct answer is "Madison"')
break
else:
print(f"Correct! Thanks for playing. It took you {attempt} attempt(s).")
All the above answers are correct, just adding a slightly different variant.
print('Quiz program!\n')
attempt = 1
max_attempts = 4
while attempt < max_attempts:
attempt += 1
answer = input('What is the capital of Wisconsin? ')
if answer == 'Madison':
print("Correct!")
break
else:
print('You got it wrong, please try again.\n')
print("Thanks for playing. It took you %s attempt(s)." %(attempt-1))
You have max_attempts = 4 - change that to 3.
You should check if the counter attempt attempt is equal to max_attempts at the beginning of the loop, before you increment the counter again, and you should set max_attempt to 3 instead:
print('Quiz program!\n')
answer = input('What is the capital of Wisconsin? ')
attempt = 1
max_attempts = 3
while answer != 'Madison':
if attempt == max_attempts:
print('You used the maximum number of attempts, sorry. The correct answer is "Madison"')
break
attempt += 1
print('You got it wrong, please try again.\n')
answer = input('What is the capital of Wisconsin? ')
else:
print(f"Correct! Thanks for playing. It took you {attempt} attempt(s).")
The problem is with your condition. It should be
attempt < max_attempts:
I also tried implementing it in a more readable way
def main():
introduction()
attempt=1
while attemptValid(attempt) and answerIsWrong(askQuestion(), attempt):
attempt += 1
def attemptValid(attempt):
max_attempts=4
if attempt < max_attempts:
return 1
print('You used the maximum number of attempts, sorry. The correct answer is "Madison"')
return 0
def answerIsWrong(answer, attempt):
if answer != 'Madison':
return 1
print(f"Correct! Thanks for playing. It took you {attempt} attempt(s).")
return 0
def introduction():
print('Quiz program!\n')
def askQuestion():
return input('What is the capital of Wisconsin? ')
main()
Surely, by adjusting the variable max_attempts to 2, 3, 4, 5 you will eventually find the right number to give you the correct behaviour. But I believe it is more important to know how to think of this issue. I would suggest to think in terms of loop invariants: Make up a condition that is always true in the loop and enforce it while you write the loop. In this case, let's make the value of attempt and the number of time of input() calls equal, and see if your loop is right:
print('Quiz program!\n')
answer = input('What is the capital of Wisconsin? ')
attempt = 1
max_attempts = 4
So your attempt set to 1 after input(). This part is OK, and satisfied the invariant (even it is before the loop). Then the loop:
while answer != 'Madison':
attempt += 1
print('You got it wrong, please try again.\n')
answer = input('What is the capital of Wisconsin? ')
if attempt == max_attempts:
print('You used the maximum number of attempts, sorry. The correct answer is "Madison"')
break
You increment attempt, then print, then call input(). I will put the attempt line right after input() call to be consistent with the code above but either case, at right before the if statement, we still have value of attempt equals to number of times we called input(). That is why you have this behaviour.
Now on how to change your code: you now knows what is "invariant" in the loop. You have to decide (1) when to do the check of attempt == max_attempts and (2) what is the right value of max_attempts to check. Other people's answer already gave you the solution.
Always scared to post here, but I'm stumped and also not sure what I'm doing wrong here, because I don't receive any errors. It appears the arguments in this function just don't work. I guess it's because it appears the conditions aren't met?
question = [f'{name}, what is 1+1', f'{name}, what is 2+2', f'{name}, what is 2+1']
answer = ['2','4','3']
def generateQuestion():
question_show = print(random.choice(question))
answer = input()
if question_show == question[0] and answer == answer[0]:
score = score + 1
print(f"Correct, your score is now {score}")
if question_show == question[1] and answer == answer[1]:
score = score + 1
print(f"Correct, your score is now {score}")
if question_show == question[2] and answer == answer[2]:
score = score + 1
print(f"Correct, your score is now {score}")
If I call that generateQuestion() function is shows the question and allows for input but nothing happens after that.
You are not comparing it correctly answer == answer[0] will never be True. If you read the input in the answer then it is no longer holds the old data.
Store the input in other variable like user_answer and the compare like user_answer == answer[0]
You haven't indented your code that is supposed to be the body of generateQuestion. Try this:
def generateQuestion():
question_show = print(random.choice(question))
answer = input()
I'm in school, and since we are rather young students, some of my 'colleagues' do not grasp what case sensitivity is. We are making a quiz in Python. Here is the code:
score = 0 #this defines variable score, and sets it as zero
print("What is the capital of the UK?")
answer = input ()
if answer == "London":
print("Well done")
score = score + 1 #this increases score by one
else:
print("Sorry the answer was London")
print("What is the capital of France?")
answer = input ()
if answer == "Paris":
print("Well done")
score = score + 1 #this increases score by one
else:
print("Sorry the answer was Paris")
print("Your score was ",score)
They are inputting 'london' as an answer instead of 'London' and still getting the answer wrong. Any workaround?
You can use .upper() or .lower()
if answer.lower() == 'london':
You can use string1.lower() on answer and you can then make a variable for London and it string1.lower().
example:
string1 = 'Hello'
string2 = 'hello'
if string1.lower() == string2.lower():
print "The strings are the same (case insensitive)"
else:
print "The strings are not the same (case insensitive)"
You can use .capitalize()
answer = raw_input().capitalize()