Starting from a certain line in python [duplicate] - python

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

Related

Using Python to make a quiz from a text file

I'm learning Python, and I need to make a mini quiz. The questions and answers are in a text file (called textfile.txt), each on its own line. At the end of the quiz, it will tell the user their score out of three.
I can get my quiz to print out the first question, and when I try inputting an answer no matter what I put (correct answer or incorrect answer), it'll tell me it's incorrect.
In the text file I have the following:
whats 1+1
2
whats 2+2
4
whats 3+3
6
And here is what I have in my .py file:
questions = open("textfile.txt", "r")
content = questions.readlines()
userScore = 0
for i in range(1):
print(content[0])
answer = input("What's the answer: ")
if answer == content[1]:
print("Correct")
userScore + 1
else:
print("Incorrect")
print(content[2])
answer = input("What's the answer: ")
if answer == content[3]:
print("Correct")
userScore + 1
else:
print("Incorrect")
print(content[4])
answer = input("What's the answer: ")
if answer == content[5]:
print("Correct")
userScore + 1
else:
print("Incorrect")
questions.close()
print("You're done the quiz, your score is: ")
print(userScore)
How do I make it read the correct answer and keep track of the users score?
First of all, use .strip() to remove the newline characters. The answers comparison might not always work because of them.
To ask every even row you can use the modulo (%) operator to get the remainder of the current line index after dividing it by two.
If the answer is correct we add 1 to the corrent_answer_count variable that we print in the end.
questions = open(r"textfile.txt", "r")
content = [line.strip() for line in questions.readlines()]
questions.close()
corrent_answer_count = 0
for i in range((len(content))):
if i % 2 == 0:
print(content[i])
answer = input("What's the answer: ")
if answer == content[i + 1]:
print("Correct")
corrent_answer_count += 1
else:
print("Incorrect")
print("Correct answer count: " + str(corrent_answer_count))

User input validation in python [duplicate]

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")

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.

Multiple choice quiz in python using random function and lists

I'm trying to make a multiple choice quiz using python. It seemed like something simple to make at first but now i'm scratching my head a lot trying to figure out how to do certain things.
I am using two lists; one for the questions and one for the answers. I would like to make it so that a random question is chosen from the questions list, as well as 2 random items from the answers list (wrong answers) and finally the correct answer (which has the same index as the randomly selected question).
I've got as far as selecting a random question and two random wrong answers
My first problem is getting the program to display the correct answer.
The second problem is how to check whether the user enters the correct answer or not.
I would appreciate any feedback for my code. I'm very new to this so go a little easy please!
I hope my stuff is readable (sorry it's a bit long)
thanks in advance
import random
print ("Welcome to your giongo quiz\n")
x=0
while True:
def begin(): # would you like to begin? yes/no... leaves if no
wanna_begin = input("Would you like to begin?: ").lower()
if wanna_begin == ("yes"):
print ("Ok let's go!\n")
get_username()#gets the user name
elif wanna_begin != ("no") and wanna_begin != ("yes"):
print ("I don't understand, please enter yes or no:")
return begin()
elif wanna_begin == ("no"):
print ("Ok seeya!")
break
def get_username(): #get's username, checks whether it's the right length, says hello
username = input("Please choose a username (1-10 caracters):")
if len(username)>10 or len(username)<1:
print("Username too long or too short, try again")
return get_username()
else:
print ("Hello", username, ", let's get started\n\n")
return randomq(questions)
##########
questions = ["waku waku", "goro goro", "kushu", "bukubuku", "wai-wai", "poro", "kipashi", "juru", "pero"]
answers = ["excited", "cat purring", "sneezing", "bubbling", "children playing", "teardrops falling", "crunch", "slurp", "licking"]
score = 0
if len(questions) > 0: #I put this here because if i left it in ONly inside the function, it didnt work...
random_item = random.randint(0, len(questions)-1)
asked_question = questions.pop(random_item)
###########
def randomq(questions):
if len(questions) > 0:
random_item = random.randint(0, len(questions)-1)
asked_question = questions.pop(random_item)
print ("what does this onomatopea correspond to?\n\n%s" % asked_question, ":\n" )
return choices(answers, random_item)
else:
print("You have answered all the questions")
#return final_score
def choices(answers, random_item):
random_item = random.randint(0, len(questions)-1)
a1 = answers.pop(random_item)
a2 = answers.pop(random_item)
possible_ans = [a1, a2, asked_question"""must find way for this to be right answer"""]
random.shuffle(possible_ans)
n = 1
for i in possible_ans:
print (n, "-", i)
n +=1
choice = input("Enter your choice :")
"""return check_answer(asked_question, choice)"""
a = questions.index(asked_question)
b = answers.index(choice)
if a == b:
return True
return False
begin()
You could structure the data in a simpler way, using dictionaries. Each item is a pair of a key and a value, for more info refer to this.
For example your data will look like this (each question is associated with an answer):
data = {'question1': 'answer1', 'question2': 'answer2'}
Then we can loop through this dictionary to print the answers after we randomly choose a question. Here's some sudo code for help:
# Choose a random question
# Print all the answers in the dictionary
for key, value in data.iteritems(): #its data.items() in Python 3.x
print value
# If the choice matches the answer
pop the question from the dictionary and do whatever you want to do
# Else, ask again
For more information about iterating through a dictionary refer to this.
You can use another list(for example correct_answer or such) to record the correct answer for each question. Then instead of using a1 = answers.pop(random_item) to choose a wrong answer, use
while True:
if answer[random.randint(0, len(answers)-1)] != correct_answer[question]:
break
a1 = answers.pop(id)
to avoid choosing the correct answer as an incorrect one.
EDIT
As your correct answer is already in the answers, you should not pop items when choosing some incorrect answers, otherwise it will break the indices.
You can choose two wrong answers and a correct answer like this.
correct = question_index
while True:
wrong1 = random.randint(0, len(answers)-1)
if wrong1 != correct:
break
while True:
wrong2 = random.randint(0, len(answers)-1)
if wrong1 != wrong2 and wrong1 != correct:
break

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?: "))

Categories