如何判断输入是否为字母?
我已经尝试解决这个问题有一段时间了,但似乎无法使其正常工作..这是我当前的工作
while True:
guess = int(raw_input('What is your number?'))
if 100 < guess or guess < 1:
print '\ninvalid'
else:
.....continue on
现在我已经做到了,因此当用户输入高于 100 或低于 1 的数字时,它会打印出“无效”。但是,如果我想让它当用户输入一个不是数字的字符串(字母、标点符号等)时它也返回这个“无效”消息怎么办?
我曾考虑过使用 if not ...isdigit() ,但它不起作用,因为我将猜测作为整数以便上述范围起作用。 Try/ except 是我想到的另一个选择,但仍然没有弄清楚如何正确实现它。
I been trying to solve this one for a while and can't seem to make it work right.. here is my current work
while True:
guess = int(raw_input('What is your number?'))
if 100 < guess or guess < 1:
print '\ninvalid'
else:
.....continue on
Right now I have made it so when a user input a number higher than 100 or lower than 1, it prints out "invalid". BUT what if i want to make it so when a user input a string that is not a number(alphabetic, punctuation, etc.) it also returns this "invalid" message?
I have thought about using if not ...isdigit(), but it won't work since I get the guess as an integer in order for the above range to work. Try/except is another option I thought about, but still haven't figured out how to implement it in correctly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用异常处理:
这样,如果用户输入非数字字符串或输入大于 100 或小于 1 的数字字符串,则将打印
\ninvalid
。编辑:< /strong> 好的,我提交给
x < y < z
语法。不过,仍然认为当它与not
一起使用时,它会失去一些魅力。You can use exception handling:
That way,
\ninvalid
will be printed if the user either inputs a non-numeric string or inputs a numeric string greater than 100 or smaller than 1.EDIT: Okay, I submit to the
x < y < z
syntax. Still think it loses some of its charm when it's used withnot
, though.