I'm studying about Sieve of Eratosthenes in python and see a command is:
for p in range(n 1):
if prime[p]:
So I want to ask you guys what is if something[p]: means. Because, during my learning python, it was not mentioned.
Thanks for your help and sorry because my english so bad.
CodePudding user response:
something[p] slices the pth element of the iterable something, if ...: checks if this element is truthy (non null number, non empty string, True, etc.) and if this is the case, evaluates the block.
CodePudding user response:
In any if-statement in python the value to the right of the if is interpreted as a boolean value, and so:
if condition:
...
is exactly the same as:
if bool(condition):
...
in your case prime[p] is being interpreted as a boolean value. The exact behaviour depends on what prime[p] represents, and indeed what prime represents. Under the assumption that prime is a list (could in principle be other types, including dict but that would be a weird design decision!) and therefore prime[p] is the pth element of the list:
prime = [True, "some string value", "", None, 12.3, 1234, 0, False]
then:
bool(prime[0])isTruebool(prime[1])isTruebool(prime[2])isFalse, since empty strings resolve toFalsebool(prime[3])isFalse, since None resolves toFalsebool(prime[4])isTruebool(prime[5])isTruebool(prime[6])isFalse, since 0 resolves toFalsebool(prime[7])isFalse, since False isFalse
For more information on how different non-boolean values are interpreted, I'd suggest looking a tutorial like this one.
