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()

Edited 6 Years Ago by HoneyBadger: n/a

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: .

Edited 6 Years Ago by Gribouillis: n/a

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.
;)

Edited 6 Years Ago by richieking: n/a

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! :)

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.
;)

Edited 6 Years Ago by richieking: n/a

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 ;)

Edited 6 Years Ago by richieking: n/a

This question has already been answered. Start a new discussion instead.