简体   繁体   English

检查用户输入后的 While/For/If Else 循环

[英]While/For/If Else Loop after checking user input

I'm new to Python and learning.我是 Python 和学习新手。 I try to write a code我尝试编写代码

  1. User input full name (with space)用户输入全名(带空格)
  2. Check duplication to a list (I used split and join to compare strings)检查列表的重复(我使用拆分和连接来比较字符串)
  3. If find a duplication, re-input new name如果发现重复,重新输入新名称
  4. If not, simple break the loop and print "Thanks"如果没有,简单地打破循环并打印“谢谢”
  5. I only need to print "Duplicated" or "Thanks" 1 time, not multiple times with For loop:(.我只需要打印一次“重复”或“谢谢”,而不是多次使用 For 循环:(。

My issue when I cant re-call the input with my code (with duplicated input) or break the loop (after new name)当我无法用我的代码(重复输入)或中断循环(在新名称之后)重新调用输入时,我的问题

list=["MT", "Smith Jenkins", "PT", "CP"]列表=[“MT”、“史密斯詹金斯”、“PT”、“CP”]

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 

Thank you.谢谢你。

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如果当前名称不同:你不能断定现在没有dup,你需要测试其他的

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因此,您可以使用for/else构造,如果在循环中没有看到break ,则将执行else ,在您的情况下,如果没有找到重复项,您将能够中断 while 循环

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM