Home > Software engineering >  How to terminate / stop a for loop
How to terminate / stop a for loop

Time:11-16

I am making a survey in Spyder. I need to make it so the output does not allow for anyone under 18 to complete the survey.... I can get it to print the error message but the survey still continues...

As you can probably tell, I am a beginner.

excluded_ages= '17''16''15''14''13''12''11''10''9''8''7''6''5''4''3''2''1''0'
age_input=input('Enter your age: ') 
print(input)
if age_input in excluded_ages:
    print('You may not proceed with this survey')
    break

postcode_input=input('Enter your postcode: ')
print(input)

I don't even know if break is the right function here, either way, it is showing up as an error because it is outside the loop... everything I type is either outside the loop or outside a function!

CodePudding user response:

Break is used to forcefully exit a loop, but an if statement is not a loop, which is why you're getting that error. Just put the rest of your survey code in an else statement:

if age_input in excluded_ages:
    print('You may not proceed with this survey')
else:
    print('Continuing survey')
    ...

CodePudding user response:

First there is no loop to break from so the break statement does nothing. Let me suggest a way to simplify this. My example will simply exit the program.

import sys

age = int(input('Enter your age: '))
if age < 18:
    print('You may not proceed with this survey')
    sys.exit()

without using packages you can do this:

age = int((input('Enter your age: '))
if age < 18:
    print('You may not proceed with this survey')
else:
    print('Starting survey...')
    # survey code here
  • Related