I would want som help on how to write some unittests/pytest in pycharm with this function:
def quiz_stats(question):
times_asked = int(question['times_asked'])
times_correct = int(question['times_correct'])
return "{:.0%}".format((times_correct / times_asked))
Doesnt need to be much, I just need an example. I dont really know how to test it, have done some easy test with a calculator and numbers, but this is hard to understand. The function returns percent for a questions in a quiz, of how many people that answer questions right. It takes info from a web-API.
import random
import requests
import pprint
url = ""
data = requests.get(url).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:
return res
else:
print("Invalid answer!")
**def quiz_stats(question):
times_asked = int(question['times_asked'])
times_correct = int(question['times_correct'])
return "{:.0%}".format((times_correct / times_asked))**
def main():
print("---------- Welcome to Python Quiz! ----------")
questions = data['questions']
random.shuffle(questions)
score = 0
games_count = 0
failed_questions = []
for question in data['questions']:
print(f"{question['prompt']} Has answered right: {quiz_stats(question)}")
res_data = {"id": "1", "correct": True}
for i, a in enumerate(question['answers'], start=1):
print(f"[{i}] {a['answer']}")
user_answer = get_numeric("> ", len(question['answers']) + 1)
if question['answers'][user_answer - 1]['correct']:
score += 1
print(f"Right!")
else:
all_correct = ", ".join(get_correct_answers(question['answers']))
res_data['correct'] = False
print(f"Wrong, right answer is: {all_correct}")
failed_questions.append((question['prompt'], get_correct_answers(question['answers'])))
games_count += 1
if games_count == 10:
break
requests.post(url, json=res_data)
print("--------------- RESULT ---------------")
print(f"You got {score} points of {games_count} possible!")
print("You answered wrong on this questions: ")
pprint.pprint(failed_questions)
if __name__ == '__main__':
main()
Aucun commentaire:
Enregistrer un commentaire