在字符串输入中输入整数时打印错误

时间:2017-10-12 15:37:46

标签: python-3.x

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

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上放什么?

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

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