繁体   English   中英

Python:使用 Str 处理用户输入异常

[英]Python: user input exception handling with Str

     while True:
        first_name = input('Please enter your first name:\n')
        last_name = input('Please enter your last name:\n')
        try:
             firstn = str(first_name)
             lastn = str(last_name)
        except ValueError:

            print('did not enter str')
            continue
        else:
            return firstn
            return lastn

我正在尝试对我的代码使用异常处理。 我想检查用户是否为名字和姓氏输入了正确的字符串值。 用户不能为他们的名字和姓氏输入数字。 如果我使用数字作为用户名,我的代码似乎忽略了 Value 错误。

您的问题在于对代码功能的理解。 当你做

first_name = input('Please enter your first name:\n')

那么first_name已经是一个代表确切用户输入的字符串。 所以你写

firstn = str(first_name)

除了复制first_name之外,实际上没有实际效果。 该字符串可能类似于"12345"但仍然是一个有效的字符串。 你想要的可能是检查字符串是否只包含字母字符,这可以通过调用.isalpha()来实现:

if not first_name.isalpha():
    raise ValueError

与您的问题没有直接关系,但也值得注意:

return firstn
return lastn

也不会产生预期的效果,因为只会执行第一个返回,导致只返回firstn 你可能想要:

return firstn, lastn

暂无
暂无

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

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