0

just a total newbie here. I am learning Python and was trying to call the function as below, yet I cannot see any output.

nums = [0,1,2,7,14]
def has_lucky_num(nums):
    #return numbers that can be divisible by 7
    for num in nums:
        if num % 7 == 0:
            return True
        return False
has_lucky_num(nums)

Can someone tell me why it did not work? Thanks in advance.

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
Hsu Myat
  • 1
  • 2

3 Answers3

2

Your program isn't printing anything because it doesn't have a print() command anywhere. Try the following line : print(has_lucky_nums(nums)), and it should print your True or False result! So you would have the following code :

nums = [0,1,2,7,14]
def has_lucky_num(nums):
    #return numbers that can be divisible by 7
    for num in nums:
        if num % 7 == 0:
            return True
        return False
print(has_lucky_num(nums))
FlyingFish
  • 111
  • 7
1

Your function has a problem:

  • You must put the return False after loop because if you don't it return immediately after checking first item So function code must be this:
nums = [0,1,2,7,14]
def has_lucky_num(nums):
    #return numbers that can be divisible by 7
    for num in nums:
        if num % 7 == 0:
            return True
    return False

If you want to see result you must print the result returns by the function has_lucky_num()

So all you have to do is to add a print like this:

Instead Of:

has_lucky_num(nums)

Replace With:

print(has_lucky_num(nums))

Output:

True
Amir Shamsi
  • 319
  • 3
  • 13
-2

Return True and Return False won't actually display anything. You need to do something with those values, for instance:

if has_lucky_num(nums) == True:
    print(f'{nums} has a lucky number!')
else:
    print(f'{nums} has a lucky number!')
```
Josh
  • 280
  • 2
  • 13
  • 2
    You don't need to change the output from True or False to something like: `print(f'{num} is a lucky...` besides the function in the question has a return value but you changed the function! – Amir Shamsi Mar 13 '22 at 06:33
  • Whoops, sleep deprived. Thanks for pointing that out. Fixed! – Josh Mar 13 '22 at 06:36