-2

I would like to know how to add user input to this code so the user can choose the topic (there will be more topics added) and difficulty instead of it having to be called at the bottom. Any explanation is much appreciated as I am quite poor with user input.

from collections import namedtuple
Question = namedtuple("Question", "question answer choices correct")

maths_questions = [Question("What is 1 + 1", "1 + 1 is 2", ["1", "2", "3", "4"], {"b", "2"}),
           Question("What is 2 + 3", "2 + 3 is 5", ["5", "4", "2", "1"], {"a", "5"})]

ansdict=[]

def quiz(questions, difficulty):
    score = 0
    for question in questions:
        global ansdict; ansdict = question.choices
        print(question.question)  
        output(difficulty, ansdict)
        users_answer = input().lower()
        if users_answer in question.correct:
            print("Correct")
            score += 1
        else:
            print("Incorrect", question.answer)  
    print("{} out of {}".format(score, len(questions)))


def output(difficulty, dicti):
    for i in range(difficulty):
        print(dicti[i])

quiz(maths_questions, 4)
khelwood
  • 55,782
  • 14
  • 81
  • 108
Valkiyare
  • 19
  • 1
  • 1
  • 6
  • 1
    Study https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output and https://stackoverflow.com/questions/1450393/how-do-you-read-from-stdin-in-python – neuhaus Nov 23 '17 at 09:49
  • Hint: Put your question lists into a `dict` so you can access them by name, eg `questions = all_questions['maths']`. – PM 2Ring Nov 23 '17 at 09:58
  • @PM2Ring Thank you, I will try - would it look like questions = all_questions[‘maths_questions’,’history_questions’] for example? :) – Valkiyare Nov 23 '17 at 10:03
  • The code in my previous comment is an example of accessing a question list from the dictionary once you've built the dictionary. To learn how to build dictionaries, take a look at [the tutorial](https://docs.python.org/3/tutorial/datastructures.html#dictionaries). If you have a small number of different question lists, you can just code them directly into your script. But if you have lots of question lists, or you want to do it more professionally, your program could read the question lists from a file. – PM 2Ring Nov 23 '17 at 10:08

2 Answers2

0

For adding inputs into code use a format such as

(Variable) = input("(Input text here)")

I'll be able to give a better example later.

0
getdifficulty= input("How hard?")
quiz(maths_questions, getdifficulty)

This is further explained here: https://www.python-course.eu/python3_input.php

jasttim
  • 723
  • 8
  • 19