作为编程的新手,我正在尝试输入名称,这是一个字符串输入。如果我输入的不是字符串,则错误应显示为无效的输入类型。怎么能实现这一目标?
答案 0 :(得分:2)
raw_input()
(Python 2)或input()
(Python 3)获取用户的意见。Type
的name
为string
,因此我们必须使用字符串方法来验证用户输入字符串。 isalpha()
字符串方法检查用户输入的字符串是否有效。代码:
name = raw_input("Enter your Last Name:")
if not name.isalpha():
print "Enter only alpha values."
输出:
:~/Desktop/stackoverflow$ python 5.py
Enter your Last Name:vivek
:~/Desktop/stackoverflow$ python 5.py
Enter your Last Name:123
Enter only alpha values.
:~/Desktop/stackoverflow$ python 5.py
Enter your Last Name:vivek 123
Enter only alpha values.
检查用户字符串的其他字符串方法是整数或alpha或两者
>>> "123".isalnum()
True
>>> "123a".isalnum()
True
>>> "123abc".isalnum()
True
>>> "123abc".isalpha()
False
>>> "123abc".isdigit()
False
>>> "123".isdigit()
True
>>> "123".isalpha()
False
按类型转换和例外方法
e.g。无效输入:
>>> a = "123a"
>>> try:
... a = int(a)
... except ValueError:
... print "User string is not number"
...
User string is not number
e.g。有效输入:
>>> a = "123"
>>> try:
... a = int(a)
... except ValueError:
... print "User string is not number"
...
>>> print a
123
>>> type(a)
<type 'int'>
>>>
如果用户输入无效值,请让用户反复输入值。
代码:
while 1:
try:
age = int(raw_input("what is your age?: "))
break
except ValueError:
print "Enter only digit."
continue
print "age:", age
输出:
vivek@vivek:~/Desktop/stackoverflow$ python 5.py
what is your age?: test
Enter only digit.
what is your age?: 123test
Enter only digit.
what is your age?: 24
age: 24
答案 1 :(得分:0)
你可以这样写一个if语句:
if not entry.isalpha():
print ("Invalid entry!")