What does for loop does after a Boolean statement?

Question:

In this snippet,what for loop does?

a = input().split()
if (all([int(i) > 0 for i in a]) and any([(i) == (i)[::-1]] for i in a)):
    print(True)
else:
    print(False)

Edit: There is a solution,you can check it out! How do Python's any and all functions work?

Asked By: Berke Balcı

||

Answers:

A structure like

[atom for atom in iterable if condition(atom)]

is a List Comprehension


Further-

any() returns True if at least one of the members of an iterable passed to it is Truthy

Together, this creates a list where each value is conditionally True and then returns whether at least one value in that new list is Truthy

The structure you provide actually does a lot more than it needs to, because the any() could be made redundant (a non-empty list is Truthy, and the condition x>0 guarantees that any entries are Truthy)

The second condition (after the and) seems to be some attempt to find palindromes by checking if the member is equal to itself reversed

>>> "1234"[::-1]
'4321'

Finally the statement itself is Truthy or Falsey, so there’s no need for an if at all, and it can be directly used/displayed immediately when found

Here’s an enterprise version

import sys

def test_substrings(sub_strings):
    for atom in sub_strings:
        if int(atom) <= 0:      # ValueError for non-int
            return False
        if atom != atom[::-1]:  # check for palindrome
            return False
    return True

sub_strings = input("enter a list of integers separated by spaces: ").split()

try:
    result = test_substrings(sub_strings)
except ValueError as ex:
    sys.exit("invalid entry (expected an integer): {}".format(
        repr(ex)))

print(str(result))

and a compact version

print(bool([x for x in input().split() if int(x) > 0 and x==x[::-1]]))

Beware: your example and mine will accept an empty input ("") as True

Answered By: ti7
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.