User input validation in python [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 11 months ago.
I've been playing about with this for a few hours now and have tried a few variations and am still getting nowhere and am not sure what I'm getting wrong. I'm trying to make it so users can only give input values of a, b or c. If anyone could advise that would be greatly appreciated. Thanks.
def run_quiz(questions):
"""
Function loops through questions and checks answer given
against correct answer. If correct answer given
then score increases by 1.
"""
score = 0
for question in questions:
answer = input(question.prompt)
answer = answer.lower()
if answer == question.answer:
score += 1
while answer not in {'a', 'b', 'c'}:
return "Invalid answer, try again"
else:
return f"You guessed {answer}"
print(f"{name} got {score} out of {str(len(questions))} questions correct")

There's no need for those return statements.
def run_quiz(questions):
score = 0
for question in questions:
answer = input(question.prompt).lower()
while answer not in {'a','b','c'}:
answer = input("Invalid answer, try again").lower()
if answer == question.answer:
score += 1
print("Correct")
else:
print("Incorrect")
print(f"{name} got {score} out of {len(questions)} questions correct")

Related

Python If always wrong [duplicate]

This question already has answers here:
How does my input not equal the answer?
(2 answers)
Closed 1 year ago.
I don't know why but when answering correctly, it always says it's not equal to the answers.
import random
a = random.randint(1,100)
b = random.randint(1,100)
answer = a + b
print(answer)
print(f"{a} + {b}")
urAnswer = input("Answer : ")
print("Your answer = " + urAnswer)
if urAnswer == answer:
print("You're Correct!")
else:
print(f"You answered {urAnswer}. Which wasn't the correct answer! The Correct Answer was {answer}")
The inputs supplied via input is of type string, Need to convert the input to int. Also you can do a validation for the input.
a = random.randint(1,100)
b = random.randint(1,100)
answer = a + b
print(answer)
print(f"{a} + {b}")
urAnswer = input("Answer : ")
print("Your answer = " + urAnswer)
if int(urAnswer) == answer:
print("You're Correct!")
else:
print(f"You answered {urAnswer}. Which wasn't the correct answer! The Correct Answer was {answer}")
You are comparing a string to an integer.
Make the answer an integer before comparing so the script will work
if int(urAnswer) == answer:

multiple choice quiz , how to deal with unwanted answer? | python

So, i have been learning from a video on youtube about basic multiple choice quiz with few possilble answers like a, b, c.
but, if the user enters r or 44 the code just wont count it as a right answer.
I want the code to print the user the question again. Ive tried to write something but now it is moving on to the next question only if the user enters the right question.
def test_run2(questions):
score = 0
for question in questions:
while True:
user_answer = input(question.prompt)
user_answer.lower()
if user_answer == "a" or "b" or "c":
if user_answer == question.answer:
score = score + 1
break
# For each of your questions
running = True
while running:
print("") # Put question in here
if answer in possibleAnswers:
# Check if correct or wrong, etc.
running = False
else:
print("Please provide a valid answer")
# Repeat again for next question
Note that this is just a snippet, you need to add the other sections of your code to it where applicable.

Not equal statement, not working [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
I am making a small quiz that has different difficulties, when doing my easy section my if statement always prints incorrect even with the correct answer - i am still new to python it might be a very easy thing to solve
How can I know if this is a duplicate if i don't know what is wrong
here is my code
def easy():
score = 0
print("Welcome to the easy section!")
print("****************************")
print("Random Access Memory(1)")
print("Radical Amazonian Mandem(2)")
qe1 = input("What does RAM stand for?: ")
if qe1 == 1:
score = score + 1
print("Well done, next question:")
if qe1 != 1:
print("Incorrect, next question:")
else:
easy()
input function return a string, you should cast it to int:
qe1 = int(input("What does RAM stand for?: "))

Starting from a certain line in python [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I am using the newest python software and I am really stumped on printing a certain line in the code.
name = input("Before we begin, what is your name? ")
print("Cool, nice to meet you "+name+"!")
score = 0
score = int(score)
count = 0
answer1 = "dogs"
answer01 = "dog"
question1 = ""
while question1 != answer1 and count < 2:
count = count + 1
question1 = input("What animal barks? ") #Asks the user a question
if question1.lower()== answer1:
print("Correct! Off to a great start, the right answer is dogs!")
score = score + 1
break
elif question1.lower()== answer01:
print("Correct! Off to a great start, the right answer is dogs!")
score = score + 1
break
elif count == 1:
print("That is wrong",name,"but you can try again. Hint: They like bones. ")
if count == 2 and question1 != answer1:
print("Incorrect again, sorry! The right answer was dogs.")
Please do correct me if that looks wrong, I am new to python. Anyway all I want to do is print the question again without repeating the introduction (start). My actual code is much longer and is an entire quiz and I need to repeat certain sections of code from different parts of the code. Please help! Plus I am sorry if the code didn't print properly when I pasted it into the my post.
So, the problem is that your questions are hardcoded, so they repeat etc. Instead, you could provide a data structure, storing all your questions, wrong ang right answers, which you would pass to some parsing logic. For example:
questions = ['What animal barks?', ...]
answers = [('dogs', 'dog'), ...]
hints = ['They like bones', ...]
def dialog(qst, ans, hnt):
score = 0
for question, answers, hint in zip(qst, ans, hnt):
incorrects = 0
while True:
usr_ans = input(question)
iscorrect = any(usr_ans.strip().casefold() == answ.strip().casefold() for answ in answers)
if incorrects < 5 or not iscorrect:
print('That is wrong, {}, but you can try again. Hint: {}'.format(name, hint))
incorrects += 1
elif incorrects >= 5:
print('Incorrect again, sorry! The right answer was {}.'.format(' or '.join(answers))
break
else:
print('Correct! Off to a great start, the right answer is {}!'.format(usr_ans))
score += 1
break
return score
It may look a bit complicated as you're starting to learn. I recommend not to code complete things, until the point in time, where you'd already known the basics. For a great start, try official Python Tutorial, and I'd recommend Lutz's Learning Python

python while loop keeps on repeating

My problem is that when you answer a question the while loop keeps on repeating until all 10 questions are answered BUT this is only true for getting the answer correct
For getting it wrong it loops on forever
correct answer:
what is
7 * 2
Answer here: 14
you got the answer right,well done
you got the answer right,well done
you got the answer right,well done
you got the answer right,well done
you got the answer right,well done
you got the answer right,well done
you got the answer right,well done
you got the answer right,well done
you got the answer right,well done
you got the answer right,well done
Welldone you have answered all 10 questions and managed to get correct: 10
press enter to exit
Wrong answer:
wrong
wrong
wrong
and this repeats on and on and it doesn't end
This is the code for the program
import random
correct,number,left,right = 0,0,random.randint(6,10),random.randint(1,5)
add =(left+right)
sub =(left-right)
mul =(left*right)
StrAdd =("+")
StrSub =("-")
StrMul =("*")
StrOp=StrAdd,StrSub,StrMul
StrRandOp=random.choice(StrOp)
print("\n\nwhat is\n",left,"",StrRandOp,"",right,)
given = float(input("\nAnswer here: "))
while number < 10:
if given == add:
print("you got the answer right,well done")
correct=correct+1
number=number+1
elif given == sub:
print("you got the answer right,well done")
correct=correct+1
number=number+1
elif given == mul:
print("you got the answer right,well done")
correct=correct+1
number=number+1
else:
print("wrong")
print("""Welldone you have answered all 10 questions and managed to get
correct:""", correct)
input("press enter to exit")
This is what you want:
import random
correct,number,left,right = 0,0,random.randint(6,10),random.randint(1,5)
add =(left+right)
sub =(left-right)
mul =(left*right)
StrAdd =("+")
StrSub =("-")
StrMul =("*")
StrOp=StrAdd,StrSub,StrMul
StrRandOp=random.choice(StrOp)
print("\n\nwhat is\n",left,"",StrRandOp,"",right,)
given = float(input("\nAnswer here: "))
while number < 10:
if given == add:
print("you got the answer right,well done")
correct=correct+1
elif given == sub:
print("you got the answer right,well done")
correct=correct+1
elif given == mul:
print("you got the answer right,well done")
correct=correct+1
else:
print("wrong")
number = number + 1
print("""Welldone you have answered all 10 questions and managed to get
correct:""", correct)
input("press enter to exit")
When you want to iterate for a specific number of times it's better to use the for loop:
for number in range(0,10,1):
print "sth"

Categories