-2

If this is correct

v = [22, 13, 45, 50, 98, 69, 43, 44, 1]
[ (x+1 if x >=45 else x+5)  for x in v ]

then what's wrong with this code?:

def isPrime(num):
is_prime = False
if num > 1:
    for i in range(2, num):
        if (num % i) == 0:
            is_prime = False
            break
    else:
        is_prime = True
else:
    is_prime = False
return is_prime


listTablesOnlyPrimes = [[ (i*num if isPrime(i*num)==True else pass) for i in range(1, 11)] for num in range(1, 11)]
for listTable in listTablesOnlyPrimes:
    print(listTable)

I want to know what's the SyntaxError in message by interpreter:

listTablesOnlyPrimes = [[ (i*num if isPrime(i*num)==True else pass) for i in range(1, 11)] for num in range(1, 11)]
                                                                  ^
SyntaxError: invalid syntax
Coder
  • 1
  • 1

2 Answers2

1

This uses a conditional expression, of the form https://docs.python.org/3/reference/expressions.html#conditional-expressions

(x+1 if x >=45 else x+5)

But this does not fit that syntax because there's no else:

(i*num if isPrime(i*num)==True)

I believe that was intended to be an if condition as part of the list comprehension syntax, but that comes at the end, as described here https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries

addendum:

not part of the question, but since you asked, here's a way to quickly add some unit testing to your code. Just put this right after your isPrime function

if not isPrime(11):
    raise ValueError("isPrime isn't right")

You do need a few more checks, but that is enough for now. I don't want to go into the whole unit test library.

Kenny Ostrom
  • 5,639
  • 2
  • 21
  • 30
  • I've actually tried that one as well but still ain't working. If you can share your working code script I will really be grateful.Thanks for replying sir. – Coder Sep 11 '20 at 20:21
  • That was the syntax error. Your isPrime function always returns false, but at least it's not a syntax error, which was the question. And the other numbers are all a product of two integers, so they have a pretty good chance to be not prime. A few of them actually should be prime like 1*7 for example, but useful trivia -- 1 itself is not prime. – Kenny Ostrom Sep 12 '20 at 00:02
  • There are plenty of other questions on how to test if a number is prime. You can look at those. – Kenny Ostrom Sep 12 '20 at 00:17
0

Problem is with if condition inside the nested list

listTablesOnlyPrimes = [[ (i*num) for i in range(1, 11) if isPrime(i*num)==True] for num in range(1, 11)]

Note:

Your code always return empty lists I don't understand why are you doing this i * num never become prime if i > 1

deadshot
  • 8,881
  • 4
  • 20
  • 39