-2

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()
dǝɥɔS ʇoıןןƎ
  • 1,674
  • 5
  • 19
  • 42
Jaskew
  • 7
  • 1
  • 4
    what error are you getting? – itzmurd4 Jun 20 '17 at 17:59
  • 1
    Is this how its indented in what your having issues running? – jacoblaw Jun 20 '17 at 18:00
  • 2
    Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. – Prune Jun 20 '17 at 18:02
  • 1
    One problem is that you use variables outside of their scope. – FamousJameous Jun 20 '17 at 18:03
  • 2
    I strongly recommend that you practice incremental programming. Write a few lines, debug those, and don't add more until you have the earlier ones fixed. The posted code has too many problems to fix in one SO question. How did you get to over 100 lines of code before you realized that you had a problem? – Prune Jun 20 '17 at 18:06
  • 1
    Having consecutive `return` statements following one another like that in a function isn't going to work like you expect. The first one is the only one that will execute (and it only returns one value). Suggest you learn Python better and not ask questions here until you do so. – martineau Jun 20 '17 at 18:07

1 Answers1

1

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:

dǝɥɔS ʇoıןןƎ
  • 1,674
  • 5
  • 19
  • 42
  • could you explain what you mean by function declarations should be put above function calls? – Jaskew Jun 20 '17 at 18:33
  • @Jaskew Retracted, see https://stackoverflow.com/questions/3754240/declare-function-at-end-of-file-in-python – dǝɥɔS ʇoıןןƎ Jun 20 '17 at 18:39
  • Hi @Jaskew if this or any answer has solved your question please consider [accepting it](https://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. _Also [here](https://stackoverflow.com/a/44306759/7304372)_ – dǝɥɔS ʇoıןןƎ Jul 11 '17 at 10:14