【问题标题】:How to create a program that terminate when numbers are inputted? [duplicate]如何创建一个在输入数字时终止的程序? [复制]
【发布时间】:2021-07-09 02:46:35
【问题描述】:
q = []
num = ["1","2","3","4","5","6","7","8","9","0"]
while True:
    dat = float(input("Enter Name: "))
    if dat == "*":
      print(q.pop(0))
    if dat in num :
    break
    else:
      q.append(dat)

#程序仅在输入 0 到 9 个数字时终止,但我希望它在输入任何数字时终止。

【问题讨论】:

    标签: python


    【解决方案1】:

    使用.isdigit()。用这种方式试试-

    q = []
    #num = ["1","2","3","4","5","6","7","8","9","0"]
    while True:
        dat = input("Enter Name: ")
        if dat == "*":
          print(q.pop(0))
        if dat.isdigit() :
            break
        else:
          q.append(dat)
    

    【讨论】:

    • @themadpsychologist 已编辑
    【解决方案2】:

    与其检查dat 是否为数字,不如检查其中的任何字符是否为数字:

    q = []
    somedigit = False
    while True:
        dat = input("Enter Name: ")
        if dat == "*":
          print(q.pop(0))
        for element in dat:
             if element.isdigit():
                 somedigit = True
                 break
        if somedigit == True:
            break
        else:
          q.append(dat)
    

    其他方法是检查函数isalpha

    q = []
    while True:
        dat = input("Enter Name: ")
        if dat == "*":
          print(q.pop(0))
        if not dat.isalpha():
          break
        else:
          q.append(dat)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多