Python Forum

Full Version: Function not returning correct value
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have been making a question/answer code with the function that follows but have fallen into trouble using the return statement.
s = 0
d = input("Enter difficulty (e/m/h)")
def question(d, score):
    print("1 + 1")
    if d == 'e':
        print("2  1")
    elif d == 'm':
        print("2  1  0")
    else:
        print("2  1  0  -1")
    answer = input("Enter the correct answer!")
    if answer == '2':
        print("Correct")
        score += 1
        print(score,"Score in code.")
    else:
        print("Incorrect the answer was 2.")
    return s #This line of code does not appear to be running.

print("question 1")
question(d, s)
print(s,"Score")
The problem I have faced involves the return statement not working so that the global variable for the score is not being increased, if the user correctly answers. I've implemented this line in other parts of the code: such as after increasing the score by one but haven't got anywhere with this. In the main code I have been using file handling instead of printing each question individually. I tried using while a loop to loop through the file however this proved difficult as the code printed every other item in the file and came up with an error. If you have any idea why this is happening for ether scenario that would be appriciated. Python v3.6.3
The return statement is not 'returning' s, because within the function, 's' is 'score' so that is what you would want to return. If you want line 22 to work, you need to modify line 21 to something like ques = question(d, s) then change line 22 to print(ques, "Score")
get away from globals it will make your (programming) life easier, and they are almost always unnecessary,
The
return s
was just a miss type. Also when the function is used twice the score isn't being updated e.g. when you get two questions right the score is still 1. Have I just made a small error or is there another way around this. Thanks for the advice TsG009
Every time you run the function, it is going to return a 1 if the answer is True. If you want it to return a cumulative value, you need to create a loop that will keep asking the question until the loop is broken (say the user hits 'x' for example) then 'return' that cumulative answer.