我如何只使用python获取整数if else条件 [英] how do I only get integer by using python if else conditional

查看:139
本文介绍了我如何只使用python获取整数if else条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

print 'enter a number'
s = raw_input()
s = float(s)
q = int(s)
if s == q:
    print 'it is an integer'
else:
    print 'it is not an integer'

当有人输入一个字符时,我还希望显示消息它不是一个整数。我怎么能这样做?

When somebody enters a character, I would also like to have the message displayed "It is not an integer". How can I do that?

推荐答案

你应该 尝试 它:

try:
    q = int(s)
    print 'it is an integer'
except ValueError:
    print 'it is not an integer'

Python哲学是请求宽恕而非许可更好 ,即尝试将 s 解析为int并捕获任何错误,而不是检查 s 是否可解析为int开始时。

The Python philosophy is "it's better to ask for forgiveness than for permission", i.e. try to parse s as an int and catch any errors as opposed to checking if s is parseable as an int to begin with.

请注意,您也可以使用 float(s)执行相同的操作。

Note that you can also do the same thing with float(s).

这篇关于我如何只使用python获取整数if else条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆