我制作了一个简单的脚本,找到一个数字的平方根。用户输入一个数字,它找到平方根并显示结果。我希望它检查输入是否是数字。如果它是一个数字,它会继续显示一条消息并重置。
我尝试使用:
while num != int(x):
print "That is not a valid number"
return self.page()
但这只会显示错误。 有人可以帮我解决这个问题吗?
以下是代码:
import math
import sys
class SqRoot(object):
def __init__(self):
super(SqRoot, self).__init__()
self.page()
def page(self):
z = 'Enter a number to find its square root: '
num = int(raw_input(z))
sqroot = math.sqrt(num)
print 'The square root of \'%s\' is \'%s\'' % (num, sqroot)
choose = raw_input('To use again press Y, to quit Press N: ')
if choose == 'Y' or choose == 'y':
return self.page()
elif choose == 'N' or choose == 'n':
sys.exit(0)
print "SqRoot Finder v1.0"
print "Copyright(c) 2013 - Ahnaf Tahmid"
print "For non-commercial uses only."
print "--------------------------------"
def main():
app = SqRoot()
app()
if __name__ == '__main__':
main()
答案 0 :(得分:8)
其中一条蟒蛇原则是EAFP:
比获得许可更容易请求宽恕。这种常见的Python编码风格假设存在有效的键或属性,并且如果假设被证明是错误则捕获异常。
x = raw_input('Number?')
try:
x = float(x)
except ValueError:
print "This doesn't look like a number!"
答案 1 :(得分:0)
如果你不想使用ask forgiveness方法,这里有一个简单的函数,可以处理任何有效的浮点数。
def isnumber(s):
numberchars = ['0','1','2','3','4','5','6','7','8','9']
dotcount=0
for i in range(len(s)):
if (i==0 and s[i]=='-'):
pass
elif s[i]=='.' and dotcount==0:
dotcount+=1
elif s[i] not in numberchars:
return False
return True
注意:您可以通过将numberchars更改为:
来轻松添加base 16numberchars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']