pythonpython-3.4

Python 3.4.1 invalid syntax?


I was doing a program that showed several prime numbers,is necessary to use functions. For example 1 at 10 = 2,3,5,7

but appear an error in the last line in the - print i- only ... I can't understand what is that

def isPrime(num):
    if num < 2:
        return False

    i = 2
    for i in range(2,int(math.sqrt(num)+1)):
        if (num % i == 0):
            return False

    return True

def main():
    print ("this program do prime numbers")
    start = int(raw_input("start number "))
    finish = int(raw_input('finish number: '))

    for i in range(start,finish):
        if isPrime(i):
            print i

Solution

  • Your problem is that you are not surrounding the i in print i with parentheses. In Python 3, print has been changed from a statement to a function. Here is your edited code:

    def isPrime(num):
        if num < 2:
            return False
    
        i = 2
        for i in range(2,int(math.sqrt(num)+1)):
            if (num % i == 0):
                return False
    
        return True
    
    def main():
        print ("this program do prime numbers")
        start = int(raw_input("start number "))
        finish = int(raw_input('finish number: '))
    
        for i in range(start,finish):
            if isPrime(i):
                print(i) #Previously "print i"
    

    Previously running:

    bash-3.2$ python3.4 prime.py
      File "test.py", line 19
        print i
              ^
    SyntaxError: invalid syntax
    bash-3.2$
    

    After editing:

    bash-3.2$ python3.4 prime.py
    bash-3.2$