Click here to Skip to main content
15,615,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am making a program and it needs to print duplicate letters from the two strings inputted by user. The output should be like "duplicate letters are: [ a, b, c]."

While if there is no duplicate letter it will just print "no duplicate letters"

My program keeps print both "duplicate letters are: [ a, b, c]." and "no duplicate letters". How do I fix it?

What I have tried:

firstName = input("What is your first name? ")
lastName = input("What is your last name? ")

for fl in firstName:
    if fl in lastName:
         print("The duplicate character in your First name and Last name is/are: ", list(fl))

else:
    print("No duplicate value for First name and Last name")
Posted
Updated 8-Mar-21 1:16am

Indentation in Python is significant: it controls flow.
So when your if and else are not indented to exactly the same level, they aren't "part of the same statement" - the for loop does not contain the else part at all!
Try this:
Python
firstName = input("What is your first name? ")
lastName = input("What is your last name? ")

for fl in firstName:
    if fl in lastName:
         print("The duplicate character in your First name and Last name is/are: ", list(fl))

    else:
        print("No duplicate value for First name and Last name")
It's a very stupid way to do things, and it's probably going to bite you many times: make sure that whatever editor you use to edit Python code is set to "replace tabs with spaces" as all whitespace counts as a single space for indentation as far as Python is concerned - which means two lines which look identically indented but which contains spaces for one and tabs for teh other can be treated very, very differently!
 
Share this answer
 
Comments
Richard MacCutchan 8-Mar-21 3:31am    
The else clause is actually connected to the for statement; another hilarious piece of Pythonese.
Maciej Los 8-Mar-21 7:29am    
5ed!
You could use a list comprehension, e.g.
Python
firstName = input("What is your first name? ")
lastName = input("What is your last name? ")

duplicates = list(set([x for x in firstName if x in lastName]))

if duplicates:
  print("The duplicate character in your First name and Last name is/are: ", duplicates)
else:
    print("No duplicate value for First name and Last name")
 
Share this answer
 
Comments
Maciej Los 8-Mar-21 7:29am    
5ed!
CPallini 8-Mar-21 12:49pm    
Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900