我将如何进行:
答案 0 :(得分:2)
强制转换为int并测试str.isalpha:
while True:
inp = raw_input() # input() python3
try:
inp = int(inp)
break
except ValueError:
if inp.isalpha():
break
print("Invalid input")
如果您确实需要两个不同的变量:
def get_name():
while True:
name = input("Enter your name: ")
if name.isalpha():
return name
print("Invalid input")
def get_age():
while True:
age = input("Enter your age")
try:
return int(age)
except ValueError:
print("Invalid input")
name = get_name()
age = get_age()
答案 1 :(得分:0)
使用isalnum内置功能。</ p>
>>> s = 'a'
>>> s.isalnum()
True
>>> s = '12'
>>> s.isalnum()
True
>>> s = '12.34'
>>> s.isalnum()
False
>>> s = 'ab12'
>>> s.isalnum()
True