【问题标题】:print error when integer is enter inside a string input在字符串输入中输入整数时打印错误
【发布时间】:2020-11-02 19:53:29
【问题描述】:

我希望有一个程序在将整数或浮点值输入字符串输入时打印出错误消息。示例:

Enter name: 1234
Invalid name entered. Please enter a new one.

Enter name: Joe
Enter no. phone:123456789

(等等..)

现在我只有这个:

while True:
    try:
        # Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
        age = input("enter name: "))
    except ValueError:
        print("Invalid name.")
        continue
    else:
        break
if : 
    print("")
else:
    print("")

我需要在 if else 中添加什么?

【问题讨论】:

标签: python-3.x


【解决方案1】:

首先创建禁止字符的字符串或集合(集合更有效),然后遍历输入字符串并检查字符是否不在forbidden_chars 集合中。如果字符串包含禁止字符,则将标志变量(在下面的示例中称为invalid_found)设置为True,并且仅在标志为False 时才跳出while 循环,这意味着如果没有找到无效字符.

forbidden_chars = set('0123456789')

while True:
    inpt = input('Enter a string: ')
    invalid_found = False
    for char in inpt:
        if char in forbidden_chars:
            print('Invalid name.')
            invalid_found = True
            break
    if not invalid_found:
        break

print(inpt)

【讨论】:

【解决方案2】:
isdigit() - it is a string method which checks that whether a string entered is numeric(only numeric, no spaces, or alphabets) or not.
    while True:
        name = input("Enter your name : ")
        if name.isdigit():
            print("Invalid name please enter only alphabets.")
            continue
        else:
            phone_number = int(input("Enter Your phone number : "))
            print(f"Name : {name}")
            print(f"Phone_number : {phone_number}")
            break

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 2016-05-14
    • 2018-12-21
    相关资源
    最近更新 更多