jmportilla / Complete-Python-Bootcamp

Lectures for Udemy - Complete Python Bootcamp Course
2.24k stars 2.94k forks source link

Functions - Prime Check in Python3 Returns Multiple Values #43

Open paper-skyline opened 6 years ago

paper-skyline commented 6 years ago

In Python3.7, entering this function and passing the number 5 to the function results in multiple return values of "True". What's causing that?

def is_prime(num):
    '''
    Naive method of checking for primes. 
    '''
    for n in range(2,num):
        if num % n == 0:
            print 'not prime'
            break
    else: # If never mod zero, then prime
        print 'prime'
>>> is_prime(5)
prime
prime
prime
abhinav4848 commented 5 years ago

this can only happen if while originally testing your function looked like

def is_prime(num):
    '''
    Naive method of checking for primes. 
    '''
    for n in range(2,num):
        if num % n == 0:
            print 'not prime'
            break
        else: # If never mod zero, then prime
            print 'prime'

instead of

def is_prime(num):
    '''
    Naive method of checking for primes. 
    '''
    for n in range(2,num):
        if num % n == 0:
            print 'not prime'
            break
    else: # If never mod zero, then prime
        print 'prime'

Note the indentation of the else clause.