Skip to main content
 首页 » 编程设计

python之防止打印某些数字

2025年05月04日14qq号

抱歉标题不好。这是我的代码:

import math 
# Finds the square root of a number 
def square_root(): 
    square_root = math.sqrt(int(raw_input('What number do you want the Square Root for'))) 
    print "The square root of is: %d " % (square_root) 

基本上,我想阻止用户输入不以 0、1、4、6、9 或 25 结尾的数字,因此我只能输出完美的正方形。我有点知道该怎么做,但我一辈子都想不起术语来进行良好的 Google 搜索,所以我来到了这里。

我知道它会涉及某种形式的 if 和类似这样的 [1:3]。

请您参考如下方法:

如果你想确保输入是一个完美的正方形,试试这样的事情:

def square_root(): 
    sqrt = int(raw_input("What number do you want the square root for? ")) ** 0.5 
    if sqrt == int(sqrt):  # i.e. 'sqrt' is an integer 
        print "Result is", int(sqrt) 
    else: 
        print "That is not a perfect square!" 

仅检查输入是否以您提到的数字结尾是不够的(如提到的评论之一)。当然,如果您仍想检查是否可以使用 str(input).endswith(SOME_VAL)。