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.
CodePudding user response:
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))
CodePudding user response:
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
CodePudding user response:
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!')
```