Anthony
Anthony

Reputation: 31

How do I make the for loop work only if one or more items != 'yes'

I'm working on a HW assignment where I create a fake club with entry questions. If any of the questions are answered with "no", then the person isn't allowed to join.

I've tried going back to the og lessons about lists and loops, but I can't find what I'm trying to do on there.

Here's my code so far.

# Purpose: Create a fake club that has certain requirements, ask user to
# fill out the application, and print out their answers + results.

def main():
    display = input('Hi! This is your application to The Aqua Project...')
    display2 = input('Read the following questions and just type y or n')

# Weird list format...
    user = [input('Are you at least 18 yrs old? '),
    input('Can you work with other people? '),
    input('Do you like animals? '),
    input('Are you okay with getting dirty sometimes? ')]



# Here's the problem, I want to print 'sorry you cant join' once...

    for i in range(4):
        if user[i] != 'y':
            print('Sorry, but you can\'t join our club')
            justToShowInCMD = input('')
            i += 1
        else:
            print('')
            print('Congratulations, you have met all of our requirements!')
            print('We will send an email soon to discuss when our team')
            print('will meet up to help save some animals!')
            print('In the meantime, visit our website at 
            TheAquaProject.com')
            justToShowInCMD = input('')

main()

When you put a 'n' for some questions it says you can join, but for others it says you can't join. I don't know why sometimes it says you can when you placed a no in the interview, it shouldn't.

Upvotes: 2

Views: 147

Answers (7)

Trenton McKinney
Trenton McKinney

Reputation: 62393

Comments on OP main():

  • A key point of programming, is code use efficiency.
    • Don't repeatedly call functions (e.g. input and print) when not necessary.
  • There are several ways your problem can be solved.
    • The other answers focus on your original user list, complete with repeatedly calling input
    • Once user executes, it essentially becomes a list of y and or n values, which you then unpack with a loop to check the values.
    • Another problem with the user list method, is it requires all of the questions to be answered, prior to disqualification. What if there were 40 questions? I'd be annoyed.
    • Incidentally, a list can be unpacked as follows: for value in user:. There is no need to address the list by index with python.

Updated main() implementation:

def print_list(values: list):
    """Print the values of a list"""
    for value in values:
        print(value)


def main():
    """Iterate through a questionnaire"""

    # Variables at the top
    intro = ['Hi! This is your application to The Aqua Project...',
             'Read the following questions and just type y or n']

    questions = ['Are you at least 18 yrs old? ',
                 'Can you work with other people? ',
                 'Do you like animals? ',
                 'Are you okay with getting dirty sometimes? ']

    final = ['\nCongratulations, you have met all of our requirements!',
             'We will send an email soon to discuss when our team',
             'will meet up to help save some animals!',
             'In the meantime, visit our website at www.TheAquaProject.com']

    print_list(intro)

    for i, question in enumerate(questions, start=1):
        response = input(question)
        if response == 'n':  # can be replaced with != 'y'
            print("Sorry, you can't join the club!")
            break
        if i == len(questions):
            print_list(final)

Comments on updated main():

  1. Instead of calling print a lot, store the text in a list and then call the print_list function to do the printing.
    • Keep custom functions separate
    • Custom functions should perform one function
    • values: list this is a type hint, which tells what data type the values parameter of print_list should be.
    • Annotations
  2. """""": use docstrings
  3. Double space between functions: How to Write Beautiful Python Code With PEP 8
  4. main(): Defining Main Functions in Python
  5. questions is obvious, it's just the questions from user, as a list without calling input
  6. unpack questions with a for-loop and use the built-in function: enumerate.
    • There are many Built-in Functions
    • i goes with enumerate to count.
    • Other languages create a dummy variable, like count = 0, then use count+=1 to track loop iteration; this is considered not pythonic. Python uses enumerate, but only if you need a count for implementing something else.
  7. if condition checks if response is n
    • If the if condition evaluates as True (e.g. when response = n, n == n is True), the user gets the sorry message, break, ends the loop, and the questionnaire is complete.
  8. There are no nicities here, the function does not check to make certain a user enters y, it only checks for n. That wasn't in the scope of the question.
  9. The start parameter of enumerate is set to 1. If all the questions are answered, i=4 and len(questions)=4 so i == len(questions) evaluates as True and the user gets the congratulations message.
    • len(questions) is used instead of 4, because it's a bad idea to hardcode in values like that, because then you have to remember you've done so. What if the number of questions changes? Then your if condition is broken.

Resources:

Upvotes: 0

a_r
a_r

Reputation: 518

Assuming you are iterating 4 times (using range(4))based on the length of user, what you can simple do is the following:

           if 'n' or 'no' in user:
               print('Sorry, but you can\'t join our club')
               justToShowInCMD = input('')
           else:
           print('')
           print('Congratulations, you have met all of our requirements!')
           print('We will send an email soon to discuss when our team')
           print('will meet up to help save some animals!')
           print('In the meantime, visit our website at 
           TheAquaProject.com')
           justToShowInCMD = input('')

You can modify the if condition to cater to other forms of negative answers like 'N' or 'No'. You don't need to iterate over user.

Upvotes: 0

Arafat Khan
Arafat Khan

Reputation: 857

I would suggest storing your questions in a list and using a for loop to ask them. Store the user's response to another list and check if there is any "n" in this list. See code below:

questions = ["Are you at least 18 yrs old?", "Can you work with other people?", "Do you like animals?", "Are you okay with getting dirty sometimes?"]
answers = list()

for question in questions:
    user_answer = input(f"[y/n] {question}: ").lower()
    answers.append(user_answer)

if "n" in answers:
    print("Sorry, you can't join our club.")
else:
    print("Congrats! You are in!!")
    # you can print your desired messages as well.

Upvotes: 0

jottbe
jottbe

Reputation: 4521

there are some small points in your code that need to be changed:

# Purpose: Create a fake club that has certain requirements, ask user to
# fill out the application, and print out their answers + results.
def main():
    display = input('Hi! This is your application to The Aqua Project...')
    display2 = input('Read the following questions and just type y or n')

    # Weird list format...
    user = [input('Are you at least 18 yrs old? '),
    input('Can you work with other people? '),
    input('Do you like animals? '),
    input('Are you okay with getting dirty sometimes? ')]
    # you define a variable inside function main
    # and assign a list to it
    # this variable will not be visible outside
    # you should just return it
    return user


# Here's the problem, I want to print 'sorry you cant join' once...
# call your function before you test the answer
# and assign the the result of the function to a
# variable you can use in your check
user= main()

# define a flag variabe to
# see if the answers are ok according your check
ok= True
for i in range(4):
    if user[i].lower()[:1] != 'y':
        # you could also use your original code
        # in the check. The code above is an example
        # how you could make sure the user can enter
        # upper/lower case letters and also "yes" 
        # and "y" [:1] cuts off 1 character
        # if the string is non-empty, otherwise it
        # returns an empty string
        print('Sorry, but you can\'t join our club')
        justToShowInCMD = input('')
        i += 1
        # memorize that some question wasn't ok
        ok= False
        # I guess here you might want to exit the loop?
        # so use a break, otherwise the other answers
        # would be checked as well and the message
        # output several times per user in some cases
        break        
if ok:
    # this code here doesn't belong in the loop body 
    # I guess. It should be executed after all questions
    # have been checked positive (which is only known
    # after the loop has been executed)
    # So here we are sure the answers were yes, because
    # otherwise we would have set ok to False
    print('')
    print('Congratulations, you have met all of our requirements!')
    print('We will send an email soon to discuss when our team')
    print('will meet up to help save some animals!')
    print('In the meantime, visit our website at TheAquaProject.com')
    justToShowInCMD = input('')

# if you call your function here, you can't check
# the result of the input() calls because
# by the time you check it it has not been entered

Upvotes: 0

John Gordon
John Gordon

Reputation: 33310

The usual ways to do this are a for loop with a break and an else clause:

for answer in user:
    if answer != 'y':
        print('Sorry')
        break
else:
    print('Congratulations')

Or the any() function:

if any(answer != 'y' for answer in user):
    print('Sorry')
else:
    print('Congratulations')

Upvotes: 2

Alex
Alex

Reputation: 1101

There are a few ways to do this:

  1. Use a flag variable and just output at the end. (Slightly inefficient if the first response is a no)
  2. Use a flag variable and a while loop to exit as soon as the user responds with no. (Can be slightly confusing)
  3. Use the builtin any method. (Can be confusing, not recommended)
flag = True

for i in range(4):
    if user[i] != 'y':
        flag = False    # User has answered no to something, set the flag to false

if flag:    # User has answered yes to everything
    # <do your `yes` output>
else:       # User has answered no to something
    # <do your `no` output>

Upvotes: 0

ToughMind
ToughMind

Reputation: 1009

If one "no" means decline, you can add break to exit the loop after print decline info. Just like:

for i in range(4):
        if user[i] != 'y':
            print('Sorry, but you can\'t join our club')
            justToShowInCMD = input('')
            # i += 1   # <<<<<<<<<<<<<<<<<< this code may be not needed here
            break      # <<<<<<<<<<<<<<<<<< where to add break
        else:
            print('')
            print('Congratulations, you have met all of our requirements!')
            print('We will send an email soon to discuss when our team')
            print('will meet up to help save some animals!')
            print('In the meantime, visit our website at 
            TheAquaProject.com')
            justToShowInCMD = input('')

or you can use a variable to indicate whether to decline, just like:

toDecline = False
for i in range(4):
        if user[i] != 'y':
            toDecline = True

if toDecline:
    print('Sorry, but you can\'t join our club')
    justToShowInCMD = input('')
else:
    print('')
    print('Congratulations, you have met all of our requirements!')
    print('We will send an email soon to discuss when our team')
    print('will meet up to help save some animals!')
    print('In the meantime, visit our website at 
    TheAquaProject.com')
    justToShowInCMD = input('')

Upvotes: 0

Related Questions