简体   繁体   中英

Python 'for' function

I am trying to write a code that returns every prime palindrome with three digits. Here is my code:

def digpalprim():
    for x in range (100,1000):
        if prime(x)=='prime':
            if str(x)==str(x)[::1]:
                return x

I've already defined the prime(x) function, it works well, that stage just determines whether x is prime or not. All in all the code works, except that it only gives me the first such a palindrome. I don't really understand why, shouldn't the program consider all the numbers between 100 and 1000? Please help?

Your function returns as soon as it finds the first such palindrome; return exits a function.

Collect your finds in a list and return that:

def digpalprim():
    palindromes = []
    for x in range (100,1000):
        if prime(x)=='prime':
            if str(x)==str(x)[::1]:
                palindromes.append(x)
    return palindromes

or you can make your function a generator by replacing the return with a yield statement :

def digpalprim():
    for x in range (100,1000):
        if prime(x)=='prime':
            if str(x)==str(x)[::1]:
                yield x

Now you'll have to iterate over this function or use list() to 'pull' all values out:

all_palindromes(digpalprim())

or

for palindrome in digpalprim():
    print(palindrome)

You are returning the function the first time you encounter one.

def digpalprim():
    palprimes = []
    for x in range (100,1000):
        if prime(x)=='prime':
            if str(x)==str(x)[::1]:
                palprimes.append(x)
    return palprimes

This creates a list at the start of the function and appends each valid palindrome prime to that list, then returns the entire list (after completing all loops) instead of returning just the first one encountered.

Just remember, if Python hits a return statement, it's going to stop function execution right there and return that value regardless of any additional loops or code you may intend to be executed.

The function returns and ends as soon as the first result is found.

You may wish to add the results to a list and then print out the list.

return x This statement causes the program to return to the calling function once this statement is encountered. To return all you may put it in an list. For eg: you can have a list called values and append it to it, and finally return it at the end

For such small tasks, I prefer using list comprehensions:

palindromes = [x for x in range(100, 1000) if (prime(x) == 'prime') and (str(x) == str(x)[::1])]

Or (equivalently):

condition = lambda f: prime(f) == 'prime' and str(f) == str(f)[::1]
palindromes = [x for x in range(100, 1000) if condition(x)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM