python: import random for multiple question - python

I have already created a login(). Trying to ask a random question each time and if answered correctly to run login().
feel that i am on the right track with the latest answer . but running into some trouble .
Below is the outline of what I am trying to do:
>>> def human_check():
random_question = random.choice(questions)
question, answer = random_question
user_answer = raw_input(question)
if user_answer != answer:
print "Sorry, try again."
else:
return login()
File "", line 5
if user_answer != answer:
^
IndentationError: unindent does not match any outer indentation level
this is what i had to begin with :
>>> def human_check():
question1 == raw_input('1+1=')#question.1#
while question1 !== '2':
print 'sorry robot , try again'
else:
return login()
question2 == raw_input('the cow jumped over the ....')#question.2#
while question2 !== '2':
print 'sorry robot , try again'
else:
return login()
import random
random.question
#
I imported the random module but how do I group the questions so that random. will work?#
SyntaxError: invalid syntax
>>>

You can do something like this:
import random
questions = []
questions.append(("1+1=", "2"))
questions.append(("the cow jumped over the ....", "moon"))
def human_check():
random_question = random.choice(questions)
question, answer = random_question
user_answer = raw_input(question)
if user_answer != answer:
print "Sorry, try again."
else:
return login()
Basically, if you maintain some list of questions, you can use random.choice to make a random selection from that list.

Related

Trying to have my program ask a question, provide an answer, and then ask a different question

I'm a total noob and a little slow on the uptake, I'm having trouble finishing this code:
def main():
question = input('What is the capital of California?: ')
print()
answer = 'Sacramento'
quiz(question, answer)
def quiz(que, ans):
if ans.upper() == que.upper():
print('That is correct! ')
else:
print(f'Sorry, the correct answer is {ans}.')
main()
I'm trying to have this program ask a question, provide the answer (if user input is wrong), ask a different question, and do the same thing. I can't figure out how to ask another question after the first question is answered. I'm trying to call the function twice.
If anyone can help me out, I'd really appreciate it.
What you can do is store the question and answer in a list and loop through it, then check user answer with answer for each question.
def main(QNA_list):
for question, answer in QNA_list: # loop through each question and answer
user_answer = input(question + " ")
quiz(user_answer, answer)
print()
def quiz(que, ans):
if ans.upper() == que.upper():
print('That is correct! ')
else:
print(f'Sorry, the correct answer is {ans}.')
# store the question and answer in a list
QNA_list = [("what is the answer of A", "a"), ("what is the answer of B", "B")]
main(QNA_list)
Gives Output
what is the answer of A a
That is correct!
what is the answer of B a
Sorry, the correct answer is B.
Your code is a good start, but there are a few naming conventions I disagree with in your code, and your code-flow seems backwards (quiz calls main and not main calls quiz).
Try the following code:
#optional: to ask questions in a random order,
#it is easy to use numpy.random.shuffle on a list of question indices
#install via the command line: py -m pip install numpy
import numpy as np
def full_quiz():
quiz_key = [
('What is the capital of California?: ','Sacramento'),
('What is the capital of New York?: ','Albany'),
('What is the capital of Texas?: ','Austin'),
('How many feet are there in one mile?: ', '5280')
]
#ask each question once in order,
for prompt,key in quiz_key:
ask_question(prompt,key)
#or,
#ask each question once in a random order
indices = list(range(len(quiz_key)))
np.random.shuffle(indices)
for index in indices:
prompt,key = quiz_key[index]
ask_question(prompt,key)
def ask_question(prompt,key):
response=input(prompt)
if response.upper() == key.upper():
print('That is correct! ')
else:
print(f'Sorry, the correct answer is {key}.')
if __name__ == "__main__":
full_quiz()
How about this.
code
import random
# Create q and a data.
data = {
1: {
'q': 'What is the capital of California? ',
'a': 'Sacramento'
},
2: {
'q': 'What is the capital of Colorado? ',
'a': 'Denver'
},
3: {
'q': 'What is the capital of Texas? ',
'a': 'Austin'
}
}
def quiz(qnum, ans):
correct_ans = data[qnum]['a']
if ans.upper() == correct_ans.upper():
print('That is correct! ')
else:
print(f'Sorry, the correct answer is {correct_ans}.')
def main():
while True:
r = random.randint(1, 3)
answer = input(data[r]['q'])
quiz(r, answer)
if answer == 'quit':
break
if __name__ == '__main__':
main()
Output
What is the capital of California? kk
Sorry, the correct answer is Sacramento.
What is the capital of California? ddf
Sorry, the correct answer is Sacramento.
What is the capital of California? r3edfd
Sorry, the correct answer is Sacramento.
What is the capital of Colorado? quit
Sorry, the correct answer is Denver.
I think this solves it:
question_list = ['question1','question2']
answer_list = ['answer1','answer2']
def main():
number = 1
question = input(f'{question_list[0]}:')
answer = answer_list[0]
for qu in question_list[1::] :
if question_list.index(qu) != len(question_list) :
if question != answer :
print(f"wrong, {answer_list[number-1]} is the answer")
question = input(f'{qu}:')
answer = answer_list[number]
number += 1
if question == answer :
print('great that is correct')
break
else :
print('your answer is correct')
break
print('im out of question sorry')
print('bye bye')
main()

Python Beginner (assistance needed) - Program only outputting one element of a saved list (3.8.1)

Python Beginner In Need Of Assistance
My program, being a true or false quiz where the user enters data which is saved, works in two parts.
Part #1: Program asks the user how many questions they have. The user then fills out a series of questions and answers for that amount. If the answer provided for a question is not (true) or (false) the program re-demands the answer. The user then saves to use this data in order to study in Part 2.
def vf():
import pickle
import random
import os
os.system('cls')
v = input("How many questions do you have : ")
vvff = list()
for i in range(0, int(v)):
v = input("Enter question : ")
while True:
f = input("Enter answer to that question (true or false) : ")
if f.lower() in ('true', 'false', 'True', 'False'):
continue
else:
print("This answer is invalid, please enter True or False")
vf = {"question": v, "answer": f}
vvff.append(vf)
question_vff = input("Would you like to save (yes or no) ")
if (question_vff == 'yes'):
pickle.dump(vvff, open("Save.dat", "wb"))
print("Saved!")
if (question_vff == 'no'):
print ("Please save to use you're data.")
Part #2: The user uses the save data from before to answer a true or false quiz. This quiz shuffles the questions and answers and the user answers each of them. If the user gets it right, the program says good job, if they get it wrong the program says wrong answer.
def vf2():
import pickle
import random
import os
os.system('cls')
vvff = pickle.load(open("Save.dat", "rb"))
random.shuffle(vvff)
for f in vvff:
print(f["question"])
response = input("What was the answer to that question? : ")
if (response == f["answer"]):
print("Good answer!")
else:
print("Wrong answer...")
print("The answer is", f, ".")
print("The study/quiz session is now over. Either create new data or try again later.")
My problem is that, in part 2, the program is supposed to shuffle the questions from the saved data and ask every single one to the user. However, it only asks for the last question they entered in part 1 of the program. What's causing this and how do I fix it? Help is greatly appreciated.
There's a little mistakes here and there so I will just go and correct them in one go:
def vf():
import pickle
import random
import os
os.system('cls')
n = input("How many questions do you have : ") #Changed v to n to avoid overlap
vvff = list()
for i in range(0, int(n)):
v = input("Enter question : ")
while True:
f = input("Enter answer to that question (true or false) : ")
if f.lower() in ('true', 'false'): #removed capitals, it's already lowercase
continue
else:
print("This answer is invalid, please enter True or False")
vf = {"question": v, "answer": f} #Moved inside for-loop
vvff.append(vf) #Moved inside for-loop
question_vff = input("Would you like to save (yes or no) ")
if (question_vff == 'yes'):
pickle.dump(vvff, open("Save.dat", "wb"))
print("Saved!")
if (question_vff == 'no'):
print ("Please save to use you're data.")
You can use := for python3.8
import os
import pickle
import random
from pathlib import Path
FILE = "Save.dat"
def clear():
os.system("cls")
def vf():
clear()
vvff = []
for _ in range(int(input("How many questions do you have: "))):
q = input("\nEnter question: ")
prompt = "Enter answer to that question (true or false): "
while (a := input(prompt)).lower() not in ("true", "false"):
print("This answer is invalid, please enter True or False")
vvff.append({"question": q, "answer": a})
tip = "\nWould you like to save [(yes)/no] "
while input(tip).strip().lower() not in ("yes", "y", ""):
print("Please save to use your data.\n")
Path(FILE).write_bytes(pickle.dumps(vvff))
print("Saved!")
def vf2():
clear()
vvff = pickle.loads(Path(FILE).read_bytes())
random.shuffle(vvff)
for qa in vvff:
print(qa["question"])
response = input("What was the answer to that question? ")
if (response == qa["answer"]):
print("Good answer!\n")
else:
print("Wrong answer...")
print(f"The answer is {qa} .\n")
print("The study/quiz session is now over. Either create new data or try again later.")
def main():
vf()
vf2()
if __name__ == "__main__":
main()

reading quiz text file no longer working

I am trying to ask the user to pick a quiz, read the relevant questions from a txt file, ask for user answers, validate and check they are correct then add up to scores. I am completely self taught so have picked this code up from various sites but as I have adapted it it no longer works - what have I done wrong? I know its probably something really obvious so please be gentle with me!
getting the message global name the_file not defined
import time
def welcome():
print ("Welcome to Mrs Askew's GCSE ICT Quiz")
print()
def get_name():
firstname = input("What is your first name?:")
secondname = input("What is your second name?:")
print ("Good luck", firstname,", lets begin")
return firstname
return secondname
def displaymenu():
print("-------------------------------------------------------")
print("Menu")
print()
print("1. Input and Output Devices")
print("2. Collaborative working")
print("3. quiz3")
print("4. quiz4")
print("5. view scores")
print("6. Exit")
print()
print("-------------------------------------------------------")
def getchoice():
while True:
print("enter number 1 to 6")
quizchoice = input()
print("You have chosen number "+quizchoice)
print()
if quizchoice >='1' and quizchoice <='6':
print("that is a valid entry")
break
else:
print("invalid entry")
return quizchoice
def main():
welcome()
get_name()
while True:
displaymenu()
quizchoice = getchoice()
print ("please chooses from the options above: ")
if quizchoice == ("1"):
the_file = open("questions.txt", "r")
startquiz()
elif quizchoice == ("2"):
collaborativeworking()
startquiz()
else:
break
def collborativeworking():
the_file = open("Collaborative working.txt", "r")
return the_file
def next_line(the_file):
line = the_file.readline()
line = line.replace("/", "\n")
return line
def next_block(the_file):
category = next_line(the_file)
question = next_line(the_file)
answers = []
for i in range(4):
answers.append(next_line(the_file))
correct = next_line(the_file)
if correct:
correct=correct[0]
explanation = next_line(the_file)
time.sleep(2)
return category, question, answers, correct, explanation
def startquiz():
title = next_line(the_file)
score = 0
category, question, answers, correct, explanation = next_block(the_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer and validate
while True:
answer =(input("What's your answer?: "))
if answer >= '1' and answer <='4':
break
else:
print ("the number needs to be between 1 and 4, try again ")
# check answer
answer=str(answer)
if answer == correct:
print("\nRight!", end=" ")
return score
main()
Couple of things I noticed. You haven't provided the error you are getting (/ problems you are having) so these are the things I noticed in my quick look:
First: enter code hereimport time should be import time
Second: All function definitions (def func():) should have the code in them indented e.g.
def get_name():
firstname = input("What is your first name: ")
Third: print () should be print()
Fourth: Multiline strings do exist
"""
Look at me mum!
WOWWWW!
"""
Fifth: It looks like a lot of this has been copied from elsewhere, if you are learning, I suggest you don't copy, but try to understand what things are doing and then hand write it
Sixth: There are a lot of bugs. I think I got most of them, but you should really change something in the way you're working. It really does fail in so many places
Seventh: Here is your code with some improvements:
import time
def welcome():
print("Welcome to Mrs Askew's GCSE ICT Quiz\n")
def get_name():
firstname = input("What is your first name: ")
secondname = input("What is your second name: ")
print("Good luck" + firstname + ", lets begin") # or print("Good luck {}, lets begin".format(firstname))
return firstname, secondname
def displaymenu():
print("""-------------------------------------------------------
Menu
1. Input and Output Devices
2. Collaborative working
3. quiz3
4. quiz4
5. view scores
6. Exit
-------------------------------------------------------""")
def getchoice():
while True:
quizchoice = input("Enter number 1 to 6: ")
print("You have chosen number " + quizchoice "\n")
if quizchoice >= "1" and quizchoice <= "6":
print("That is a valid entry")
break
else:
print("invalid entry")
return quizchoice
def main():
welcome()
get_name()
while True:
displaymenu()
quizchoice = getchoice()
print("Please chooses from the options above: ")
if quizchoice == ("1"):
the_file = open("questions.txt", "r")
startquiz()
elif quizchoice == ("2"):
collaborativeworking()
startquiz()
else:
break
def collborativeworking():
the_file = open("Collaborative working.txt", "r")
return the_file
def next_line(the_file):
line = the_file.readline()
line = line.replace("/", "\n")
return line
def next_block(the_file):
category = next_line(the_file)
question = next_line(the_file)
answers = []
for i in range(4):
answers.append(next_line(the_file))
correct = next_line(the_file)
if correct:
correct = correct[0]
explanation = next_line(the_file)
time.sleep(2)
return category, question, answers, correct, explanation
def startquiz():
title = next_line(the_file)
score = 0
category, question, answers, correct, explanation = next_block(the_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer and validate
while True:
answer =(input("What's your answer?: "))
if answer >= '1' and answer <='4':
break
else:
print ("the number needs to be between 1 and 4, try again ")
# check answer
answer=str(answer)
if answer == correct:
print("\nRight!", end=" ")
return score
main()
Eighth: Please take time to make an answer before you post. People here want to answer questions, and try to answer them with the most effort they can put in, so we expect questioners to put in the same effort, to spend time on their questions (basically pretend you are asking the person you respect most in your life this question, then behave appropriately e.g. Dear your royal highness, beloved master and benefactor, who I so dearly love, please, oh please, do me the great kindness to answer my humble question that I have taken 2 days to write properly so you wouldn't be offended and have to waste as little time as possible with such a small thing as me...)
Ninth: There are much better ways to do what you want.
I suggest you:
Try perfecting parts of your program, before writing 108 lines
Try not having so many functions
Try to decrease the length of your code, make it not so verbose, but succinct
Use consistent formatting (e.g. only one type of quotes; only, spaces or tabs)
Also read up on some basic python (learn python the hard way is good)
I also highly recommend PEP (Python Enhancement Proposals) 8 and the other PEP's
Look at test-driven development in python

Int is not callable

I have researched this subject, and cannot find a relevant answer, here's my code:
#Imports#
import random
from operator import add, sub, mul
import time
from random import choice
#Random Numbers#
beg1 = random.randint(1, 10)
beg2 = random.randint(1, 10)
#Variables + Welcoming message#
correct = 0
questions = 10
print ("Welcome to the Primary School Maths quiz!!")
print ("All you have to do is answer the questions as they come up!")
time.sleep(1)
#Name#
print("Enter your first name")
Fname = input("")
print ("Is this your name?" ,Fname)
awnser = input("")
if awnser == ("yes"):
print ("Good let's begin!")
questions()
if input == ("no"):
print("Enter your first name")
Fname = input("")
print ("Good let's begin!")
#Question Code#
def questions():
for i in range(questions):
ChoiceOp = random.randint (0,2)
if ChoiceOp == "0":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1*beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
if ChoiceOp == "1":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1-beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
if ChoiceOp == "2":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1+beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
questions()
If I'm perfectly honest I'm not quite sure what's wrong, I have had many problems with this code that this wonderful site has helped me with, but anyway this code is designed to ask 10 random addition, subtraction and multiplication questions for primary school children any help I am thankful in advance! :D
You have both a function def questions() and a variable questions = 10. This does not work in Python; each name can only refer to one thing: A variable, a function, a class, but not one of each, as it would be possible, e.g. in Java.
To fix the problem, rename either your variable to, e.g., num_questions = 10, or your function to, e.g., def ask_question()
Also note that you call your questions function before it is actually defined. Again, this works in some other languages, but not in Python. Put your def quesitons to the top and the input prompt below, or in another function, e.g. def main().

Is there an "ignore" function for Python 2.7?

total newbie here.
So is there any way to stop a functioning from being executed if certain condition is met?
Here is my source code:
answer = raw_input("2+2 = ")
if answer == "4":
print "Correct"
else:
print "Wrong answer, let's try something easier"
answer = raw_input("1+1 = ")
if answer == "2":
print "Correct!"
else:
print "False"
So basically, if I put 4 on the first question, I will get the "False" comment from the "else" function below. I want to stop that from happening if 4 is input on the first question.
Indentation level is significant in Python. Just indent the second if statement so it's a part of the first else.
answer = raw_input("2+2 = ")
if answer == "4":
print "Correct"
else:
print "Wrong answer, let's try something easier"
answer = raw_input("1+1 = ")
if answer == "2":
print "Correct!"
else:
print "False"
You can place the code inside a function and return as soon any given condition is met:
def func():
answer = raw_input("2+2 = ")
if answer == "4":
print "Correct"
return
else:
print "Wrong answer, let's try something easier"
answer = raw_input("1+1 = ")
if answer == "2":
print "Correct!"
else:
print "False"
output:
>>> func()
2+2 = 4
Correct
>>> func()
2+2 = 3
Wrong answer, let's try something easier
1+1 = 2
Correct!

Categories