1

The function is supposed to load a list and print the sum of the first and last primes in the list. I have written it so that a new list is made and the idea i that only primes are appended to it - if its not a prime, it should go back to the beginning of that for loop. I want my function to go back to the beginning of the for loop after

if L[i] % j == 0:

as I only want prime numbers to be appended to y, but I don't think 'break' is the right thing to do here as I keep having my entire list being printed when I call the function. I've tried 'break', 'pass', 'continue' and an infinite loop (although I may not have done that correctly). Please help???

def first_plus_last_prime(L):
    y = []
    for i in range(len(L)):

        if L[i] < 2:
            break
        for j in range(2, L[i]):
            if L[i] % j == 0:
                break
        y.append(L[i])

    print(y)
    print(y[0])
    print(y[-1])
    t = y[0] + y[-1]
    return t
1
  • 1
    Just a suggestion: There is codereview.stackexchange.com. After fixing your code, consider posting it there. Apart from the problem with the implementation itself, there are a bunch of other things that could be improved. Commented Mar 9, 2019 at 19:42

1 Answer 1

2

You can use the else statement:

def first_plus_last_prime(L):
    y = []
    for i in range(len(L)):

        if L[i] < 2:
            break

        # Look for prime
        for j in range(2, L[i]):
            if L[i] % j == 0:
                break
        else:
            y.append(L[i])

    print(y)
    print(y[0])
    print(y[-1])
    t = y[0] + y[-1]
    return t

Thanks to @UlrichEckhardt for the info. https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

Sign up to request clarification or add additional context in comments.

3 Comments

I just answer your question about how to do in case that the number doesn't prime. But why you break the loop when you find a 0 or 1? If you do that you are not going to look the whole list.
Python allows else after a for-loop. Much more elegant and exactly invented for situations like this. docs.python.org/3/tutorial/…
@UlrichEckhardt Thank you for the info, I edit the answer to show that way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.