I’m new to Python and learning. I’m trying to write a program to:
- User input full name (with space)
- Check duplication to a list (I used split and join to compare strings)
- If find a duplication, re-input new name
- If not, simply break the loop and print “Thanks”
- I only need to print “Duplicated” or “Thanks” 1 time, not multiple times with For loop.
My issue is when I cant re-call the input with my code (with duplicated input) or break the loop (after new name)
list=["M T", "Smith Jenkins", "P T", "C P"] while True: user=input("Your full name :") usercheck="".join(user.split()) print(usercheck) for i in list: j="".join(i.split()) if usercheck ==j: print("Duplicated ! Please enter new name") else: print("Thanks") break
Advertisement
Answer
You need to think about that
- if the current name in the iteratation is same :that’s a dup
- if the current name is different : you can’t conclude there is not dup now, you need to test the others
So you can use the for/else
construction, the else
will be executed if no break
has been seen in the loop, in your case if no duplicated has been found, there you’ll be able to break the while loop
names = [] while True: user = input("Your full name :") usercheck = "".join(user.split()) print(usercheck) for name in names: j = "".join(name.split()) if usercheck == j: print("Duplicated ! Please enter new name") break else: print("Thanks") break
If that is too tricky, you can keep with a variable that will help you know whether you’ve seen a duplicate or not
while True: user = input("Your full name :") usercheck = "".join(user.split()) duplicated = False for name in names: j = "".join(name.split()) if usercheck == j: print("Duplicated ! Please enter new name") duplicated = True break if duplicated: print("Thanks") break