I want to get 10 random questions from an web API with many questions, but I dont seem to get it to work. Right now im getting KeyError: 'prompt', but I dont know if the function is correct at all as I have been trying a few diffrent options.
Im also trying to print out in the end which questions you get wrong, but with no luck there either.
import random
import requests
from random import randint
url = ""
the_questions = requests.get(url).json()
print("------ Welcome to Python quiz ------")
def random_question():
data = the_questions['prompt']
random_index = randint(0, len(data)-1)
return data[random_index]['prompt']
def get_correct_answers(answers):
res = []
for ans in answers:
if ans['correct']:
res.append(ans['answer'])
return res
def get_numeric(prompt, max_value,):
while True:
try:
res = int(input(prompt))
except ValueError:
print("Answer only with a number!")
continue
if 0 < res < max_value:
break
else:
print("Invalid answer option!")
return res
def main():
score = 0
for questions in the_questions['questions']:
#print(questions['prompt'])
print(random_question())
for i, a in enumerate(questions['answers'], start=1):
print(f"[{i}] {a['answer']}")
user_answer = get_numeric("> ", len(questions['answers']) + 1)
if questions['answers'][user_answer - 1]['correct']:
score += 1
print(f"Right!")
else:
all_correct = ", ".join(get_correct_answers(questions['answers']))
print(f"Wrong, right is: {all_correct}")
print(f"You got {score} points of {len(the_questions['questions'])} possible!")
if __name__ == '__main__':
main()
Sample of the API
{"questions":[{"id":"1","prompt":"Which functions is used to write out text in the terminal?","answers":[{"answer":"print","correct":true},{"answer":"input","correct":false},{"answer":"import","correct":false},{"answer":"sys.exit","correct":false}]}
Error shows problem with key prompt and you use it only in random_question().
If you use print() to see values in variables random_question() then you will see that you need
data = the_questions['questions']
instead of
data = the_questions['prompt']
As for me name of variables are missleading. You should use name data for all information from API and later questions = data['questions'] could make sense.
EDIT:
My version with random.shuffle()
import random
#import requests
import json
def get_correct_answers(answers):
res = []
for ans in answers:
if ans['correct']:
res.append(ans['answer'])
return res
def get_numeric(prompt, max_value,):
while True:
try:
res = int(input(prompt))
except ValueError:
print("Answer only with a number!")
continue
if 0 < res < max_value:
break
else:
print("Invalid answer option!")
return res
def main():
print("------ Welcome to Python quiz ------")
#url = ""
#data = requests.get(url).json()
data = json.loads('''
{"questions":[
{"id":"1","prompt":"Which functions is used to write out text in the terminal?","answers":[{"answer":"print","correct":true},{"answer":"input","correct":false},{"answer":"import","correct":false},{"answer":"sys.exit","correct":false}]},
{"id":"2","prompt":"Which functions is used to read text from the terminal?","answers":[{"answer":"print","correct":false},{"answer":"input","correct":true},{"answer":"exec","correct":false},{"answer":"load","correct":false}]}
]}
''')
questions = data['questions']
random.shuffle(questions)
score = 0
for question in questions:
print(question['prompt'])
answers = question['answers']
for i, a in enumerate(question['answers'], 1):
print(f"[{i}] {a['answer']}")
user_answer = get_numeric("> ", len(answers)+1)
if answers[user_answer-1]['correct']:
score += 1
print(f"Right!")
else:
all_correct = ", ".join(get_correct_answers(answers))
print(f"Wrong, right is: {all_correct}")
print(f"You got {score} points of {len('questions')} possible!")
if __name__ == '__main__':
main()
Related
I'm new to Python, and i'm programming a simple math question program. The user is prompted a math question, and the user have to type the correct answer. All of the questions, solutions and answers are saved to a local excel ark. That is the summary of my project, now comes the problem:
When i append resultsArr the question column is blank in the excel ark. When i print resultArr i get an array back with the question as the first index in the array.
So i get an array back with all of the values, but for some reason it doesn't accept the first index. I have tried to manually write a string in its place, and that works.
main.py - current version
from colors import colors
from mathQuestion import mathQuestion
from openpyxl import Workbook
gameResults = []
score = 0
def saveData(rows):
wb = Workbook()
ws = wb.active
ws.append(["Question", "Answer", "Solution"])
[ws.append(x) for x in rows]
wb.save("data.xlsx")
wb.close()
while True:
result = mathQuestion()
gameResults.append(
[result["question"], result["answer"], result["solution"]])
if(result["answer"] == result["solution"]):
score += 1
print(f"{colors.green}Correct{colors.default}, your current score: {colors.yellow+str(score)+colors.default}")
else:
print(colors.red+"Game Over"+colors.default)
break
saveData(gameResults)
mathQuestion.py
from random import randint
from colors import colors
def oddOrEven():
number = randint(1, 1000)
numberIsOdd = number % 2 != 0
question = f"Is {number} odd or even: "
if(numberIsOdd):
solution = "odd"
else:
solution = "even"
while True:
userInput = input(question)
if(userInput == "odd" or userInput == "even"):
return {
"answer": userInput,
"question": question,
"solution": solution
}
else:
print("Only odd or even")
def muliply():
a = randint(0, 10)
b = randint(0, 10)
question = f"What is {a} * {b}: "
solution = a*b
while True:
userInput = input(question)
try:
return {
"answer": int(userInput),
"question": question,
"solution": solution
}
except:
print("Only numbers are allowed")
mathFunctions = [
oddOrEven,
muliply
]
def mathQuestion():
return mathFunctions[randint(0, len(mathFunctions)-1)]()
Github repo
This program essentially encodes and decodes a message and code respectively. I only did the decoding part so far. However I keep getting an EOF error even though I made sure to end parentheses, checked my syntax and kept tampering with it. Unfortunately no luck. Anyone know why this error keeps popping up? I would greatly appreciate it. Also I copied both files that i'm using.
from LetterCodeLogic import LCL
def main():
print("Welcome to the LetterCode program")
choice = getChoice()
while choice !=0:
if choice == 1:
#Encode logic...
print()
elif choice == 2:
#Decode logic...
msg = input("Enter your numbers to decode (separate with commas): ")
#send msg to Decode function in LCL class (LetterCodeLogic.py file)
result = LCL.Decode(msg)
print("Your decoded message is: \n" + result)
else:
print("Unknown process...")
print()
choice = getChoice()
print("Thanks for using the Letter Code program")
def getChoice():
c = int(input("Choice? (1=Encode, 2=Decode, 0=Quit): "))
return c
if __name__ == "__main__":
main()
class LCL:
"""Encode/Decode Functions"""
#staticmethod
def Decode(msg):
#separate numbers from msg string (e.g., "1,2,3")
nums = msg.split(",") #produces list of separate items
result = ""
for x in nums:
try:
n = int(x.strip()) #remove leading/trailing spaces...
if n == 0:
c = " "
elif n < 0 or n > 26:
c = "?"
else:
#ASCII scheme has A=65, B=66, etc.
c = chr(n+64)
except ValueError:
c = "?"
result += c #same as: result = result + c
return result
#staticmethod
def Encode(msg):
the "#staticmethod" and "def Encode()" function was empty and that was the end of line parsing error. When I was coding this and ran it, it ran with no problems. So I removed it for the time being.
Sometimes it works fine, sometimes throws an error. Cannot figure it out. No matter how many inputs.
Thats the error. Is it the order of the code or something else?
give_gift.remove(reciever)
ValueError: list.remove(x): x not in list
Code:
import random
import os
import time
random.seed()
buy_gift = []
give_gift = []
names = True
print('Add name, then press ENTER. To finish type "end".')
while names is True:
name = input()
if name == "end":
if len(buy_gift) < 2:
print("Go play with your own gift. Goodbye!")
print()
os.system("PAUSE")
quit()
else:
names = False
else:
buy_gift.append(name)
give_gift.append(name)
exchange = len(give_gift)
os.system("cls")
time.sleep(1)
print("Drawing pairs...")
print()
time.sleep(1)
while exchange > 0:
giver = random.choice(buy_gift)
reciever = random.choice(give_gift)
while giver == reciever:
reciever = random.choice(buy_gift)
print(giver,"buys gift for",reciever)
time.sleep(0.25)
buy_gift.remove(giver)
give_gift.remove(reciever)
exchange -= 1
print()
os.system("PAUSE")
There is an issue with this line:
while giver == reciever:
reciever = random.choice(buy_gift)
It should be:
reciever = random.choice(give_gift)
I'm trying to make a an input timer on a question that gives the user 5 seconds to answer the question before deciding that no input is the same as the wrong answer, but no body wants to touch it with a 10ft pole, so I'm trying to go about it a different way and break a for loop with input?
Any one got suggestions?
import random
import operator
qLimit = 10
oqLimit = 10
score = 0
maxNum = 10
timeLimit = 0
otimeLimit = 5
import time
ops = {
'+':operator.add,
'-':operator.sub
}
def generateQuestion():
x = random.randint(1,maxNum)
y = random.randint(1,maxNum)
op = random.choice(list(ops.keys()))
a = ops.get(op)(x,y)
print("What is {} {} {}?\n".format(x, op, y))
return a
def askQuestion(a):
timeLimit = otimeLimit
for i in range(0,timeLimit):
guess = input("")
print (timeLimit - i)
time.sleep(1)
if timeLimit == 0:
try:
integer_input = int(guess)
except ValueError:
print('Please enter a valid number')
return
global score
if integer_input == a:
print("Correct!")
score += 1
else:
print("Wrong, the answer is",a)
while qLimit != 0:
askQuestion(generateQuestion())
qLimit -= 1
print ("You have", qLimit, "questions remaining")
print("Your score is",score)
if (qLimit == 0):
break
Adapting the example from the Python docs:
import signal
class OutOfTime(Exception):
"too slow"
def handler(signum, frame):
raise OutOfTime("no input received")
try:
# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)
ans = input('What is your favorite color? ')
signal.alarm(0)
except OutOfTime:
print('\nout of time! too slow!')
else:
print('%s, huh? Mine, too!' % ans)
So I have to create a program that asks the user 5 addition questions and they can type the right answer. I am very new at python and functions in general so helpful answers only please. I know how to get random numbers and make it so the question for ex: "What is 4 + 5?" I just do not know how to ask 5 different addition questions within the function. This is what I have.
import random
def add():
num1=random.randint(1,10)
num2=random.randint(1,10)
return num1,num2
def main():
x,y= add()
plus=int(input("What is {} + {} ?".format(x,y)))
main()
I don't get an error when I run your code. Here is an answer for you:
Right now your main() is asking for an input back from the user and each time main() is called it will ask for a different number, so if you like you can do something like this:
for _ in range(5):
main()
But from the sound of it, you want to have the function main() ask all of the questions, namely - something like this:
def main():
for _ in range(5):
x,y = add()
plus = int(input("What is {} + {} ?".format(x,y)))
Simplest is to use a counting loop:
def main():
for i in range(5):
x,y = add()
plus = int(input("What is {} + {} ?".format(x,y)))
The following program demonstrates how to have a program ask five addition questions:
import random
import sys
def main():
for count in range(5):
ask_addition_question()
def ask_addition_question():
numbers = random.randrange(10), random.randrange(10)
answer = get_number('What is {} + {}? '.format(*numbers))
total = sum(numbers)
if answer == total:
print('That is correct!')
else:
print('Actually, the correct answer is {}.'.format(total))
def get_number(query):
while True:
try:
return int(input(query))
except KeyboardInterrupt:
print('Please try again.')
except EOFError:
sys.exit()
except ValueError:
print('You must enter a number.')
if __name__ == '__main__':
main()
Just use a for loop to ask the user 5 times
def main():
for i in range(5):
x,y = add()
plus = int(input("What is {} + {} ?".format(x,y)))
To check if the answer is correct just you can do:
if x + y == plus: print "good"
else: print "bad"