2

I can not get the answers I need from the "duplicates"

I have made a while-loop that asks the user several questions, because I want the survey to run over again until the user inputs for the survey to break. I have made a function, and after every question, this function is ran through with the answer. If the answer says "break" (or "hade"), the while-loop should stop running

def check_answer(element):
if str(element) == "break":
    return exit()

This function works, put it does not let the program put out the statistics of the program, due to quitting all together. I have found out that I am not allowed to

return break

so I don't know what to do. For reference, here is the entire code. Some of it is in Norwegian, but the relevant parts are the function, the while-loop, and the print-statements (the ones that wont be printed using quit())

I have also tried to use a True/False statement to fix this, but I have not succeeded:

def sjekk_svar(element):
if str(element) == "hade":
    global to_continue
    to_continue = False
    return to_continue

As said, this will not work. Here is the full code:

def sjekk_svar(element):
if str(element) == "hade":
    return quit()

while to_continue == True:

    # Sex
    kjonn = input("Er du mann eller kvinne? ")
    *sjekk_svar(kjonn)             # Calling the function
    while kjonn != "mann" and kjonn != "kvinne":
        kjonn = input("Er du mann eller kvinne? ")
        sjekk_svar(kjonn)             # Calling the function
        if kjonn != "mann" and kjonn != "kvinne":
            print("Feil input. Vennligst oppgi kjønn som mann eller kvinne")

    # Age
    alder = input("Hva er alderen din? ")
    sjekk_svar(alder)             # Calling the function
    if (int(alder) > intervall_high or int(alder) < intervall_low):
        print("Du er ikke innenfor aldersgruppen til denne undersøkelsen. Vennligst gi PC-en til noen andre.")

    # Q1, 2 ,3

   fag = input("Tar du noen universitetsfag? [ja/nei] ")
    sjekk_svar(fag)             # Calling the function
    if fag == "ja" and int(alder) < 22:
        itgk_medlem = input("Tar du faget ITGK? ")
        sjekk_svar(itgk_medlem)             # Calling the function
    elif fag == "ja" and int(alder) >= 22:
        itgk_medlem = input("Tar virkelig du ITGK? ")
        sjekk_svar(itgk_medlem)             # Calling the function
    timer_lekser = input("Hvor mange timer om dagen bruker du i snitt på lekser? ")
    sjekk_svar(timer_lekser)             # Calling the function

    # Start over again
    print("Velkommen til ny spørreundersøkelse!")

    # Assigning values of amount of surveys completed
    ant_fag +=1
    ant_timer += int(timer_lekser)
    if kjonn == "mann":
        menn += 1
    if kjonn == "kvinne":
        kvinner += 1
    if itgk_medlem == "ja":
        ant_itgk += 1


# Printing the statistics
print("Resultatet av spørreundersøkelsen er som følger:")
print("Antall kvinner:", str(kvinner))
print("Antall menn:", str(menn))
print("Antall personer som tar et fag:", str(fag))
print("Antall personer som tar ITGK:", str(ant_itgk))
print("Antall timer i snitt brukt på lekser:", str(ant_timer/(kvinner+menn)))
vault
  • 124
  • 1
  • 9

2 Answers2

0

Just return a boolean to signal whether you should break:

def should_i_break(value):
    if value:
        return True
    return False

for i in range(10):
    print(i)
    if should_i_break(i == 6):
        break

or, more simply,

def should_i_break(value):
    return value == 6

for i in range(10):
    print(i)
    if should_i_break(i):
        break

which give:

0
1
2
3
4
5
6

I think of functions as being "black boxes" that take inputs, perform tasks and possibly return values. Since there is no way of inputting that you are in a for-loop, the function has no way of knowing if it is in a for-loop, hence it cannot break out of it. Thus the only way of communicating to the for-loop scope that this function says that we should break out is by returning a value (a boolean here) that the other code can interpret and break if necessary.


And, as Martijn points out, if the "breaking function" really was as simple as one if-statement, it is unnecessary and overly complicated to break the code up into that function. Instead, you should just use that if-statement in the for-loop. However, I think you know this an your question was about how one would go about breaking from within a function (if the function was longer and had more to it).

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
  • 1
    Why not just use `if i == 6: break` then? Don't use `return True` / `return False` for something that is **already** a boolean value. – Martijn Pieters Oct 12 '18 at 12:41
  • So, yes, while this is super simple example of a function and addresses the *you can't use break in a function* problem, it's also bad practice and should at least be addressed to avoid the whole `if boolean: return True` / `else: return False` anti-pattern. – Martijn Pieters Oct 12 '18 at 12:44
  • @MartijnPieters My point was to demonstrate the logic! Of course the code would never be this simple, but the `should_i_break` function would contain much more in the real case. – Joe Iddon Oct 12 '18 at 12:44
  • At which point you would use: `should_i_break(i)`, and `return i == 6` (with the `if i == 6: return True` / `return False` version as an intermediary in the explanation, if used at all). – Martijn Pieters Oct 12 '18 at 12:45
  • @MartijnPieters I take your point, will update. – Joe Iddon Oct 12 '18 at 12:48
-1

A function can't return a statement. Instead, you can have your function return a Boolean value and use if statements in your code:

def check_answer(element):
    return str(element) == "break"

# multiple times in your code
if check_answer(value):
    break
jpp
  • 159,742
  • 34
  • 281
  • 339