通过raw_input()(Python 2)或input()(Python 3)从用户获取输入。
^变量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
按类型转换和异常方法
例如,对于无效输入:>>> a = "123a"
>>> try:
... a = int(a)
... except ValueError:
... print "User string is not number"
...
User string is not number
例如,对于有效输入:>>> a = "123"
>>> try:
... a = int(a)
... except ValueError:
... print "User string is not number"
...
>>> print a
123
>>> type(a)
>>>
如果用户输入的值无效,则要求用户反复输入值。
代码: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