Guys I wrote a program that creates 23 random numbers(birthdays)
and the counts how many duplicates are there.
How come sometimes when I run this it returns "None"?

Here is the code:

import random

#Checks for duplicates.
def has_duplicates(userstring):
    userlist = list(userstring)
    list_len = len(userlist)
    len_no_duplicates = len(set(userlist))
    if list_len != len_no_duplicates:
        return True
    return False

def bdays_23():
    birthdays = []
    while len(birthdays) <= 23:
        birthdays.append(random.randint(1, 365))
    return birthdays

def in_common():
    if has_duplicates(bdays_23()) == True:
        return len(bdays_23()) - len(set(bdays_23()))
    
        

def main():
    """
        main function
    """
    print in_common()
   
    return 0

if __name__ == "__main__":
    main()

In the function in_common() when the if fails, there is no return statement, so it returns None.


Also in most situations you don't need if expression == True . Simply write if expression: .

Check your logic well.

Your code will not do waht you expects. Try something that takes real data as you will only have either True or false for the whole bunch .

Doesnt worth it.
Check it up again.
;)

In the function in_common() when the if fails, there is no return statement, so it returns None.


Also in most situations you don't need if expression == True . Simply write if expression: .

Thanks Gribouillis! :)

when will the 'if' fail, can i have an example?

The if will fail once the object is equal to 0/Null.

The logic is
1. you checked for a condition if it is True.
2. if the condition is not.... then branch.

To check for True condition with if... You do not repeat True as if default condition check is True. So repeating True again does not make any impact.
Hope you get it.
;)

Look at this example. The if was not tested with True

word="The lazy fox jump over the fence"

word=word.split()
for x in word:
    if x:
      print x
print ("X now is finished, X is null or zero")

Just play around stuff you will get it ;)

thanks richieking for your answer

well you are always welcome buddy. i was once like you ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.