数字的平方根在Python中

时间:2017-07-06 17:22:44

标签: python

我创建了一个程序,您可以在其中掷骰子或查找数字的平方根。这些选项可以用数字1和2切换。但是,每当我想找到一个数字的平方根时,它就会给出我想要的数字的平方根和2的平方根。如何解决这个问题?代码如下: 请忽略缩进错误,因为Stack Overflow让我很难把代码放进去。

from random import randint
import math

UserInput = int(input("To Roll A Dice, Type One. To Find The Square Root Of A 
Number, Press 2 "))
    while True:
        if UserInput == 1:
            print (randint(1, 6))

        if UserInput == 2:
            print(math.sqrt(int(input("What Number Would You Like To Find The Square Root Of? "))))

当我想找到16的平方根时,这是我的结果:

 To Roll A Dice, Type One. To Find The Square Root Of A Number, Press 2 2
 What Number Would You Like To Find The Square Root Of? 16
 4.0
 1.4142135623730951

1 个答案:

答案 0 :(得分:2)

您的代码的主要问题是评论中所述的不良缩进。另外,我认为不需要无限循环,因为它会反复滚动并重复平方根,除非这是你的目标。 这是我的代码:

from random import randint
import math

UserInput = int(input("To Roll A Dice, Type One. To Find The Square Root Of A Number, Press 2 "))
if UserInput == 1:
    print (randint(1, 6))

elif UserInput == 2:
    print(math.sqrt(int(input("What Number Would You Like To Find The Square Root Of? "))))

除非您想反复询问用户输入,否则将while循环置于创建User Input变量之上。

编辑:如果你真的想要重新使用,那么使用def使这成为一个函数并拥有以下代码

while True:
    play = input("Do you want to play? y/n")
    if play == "y":
        function_name()
    elif play == "n":
        break
相关问题