Square Root Of A Number In Python

Question:

I created a program where you can either roll a dice or find the square root of a number. These options can be toggled with the numbers 1 and 2. Howvever, whenever I want to find the square root of a number, it gives me the square root of the number I want and the square root of 2. How do I solve this? Code is below:
Please disregard indentation errors as Stack Overflow was giving me a tough time putting the code in.

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? "))))

And This is my Result when I want 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
Asked By: How To Tutorials

||

Answers:

The main issue with your code as bad indentation as stated in the comments. In addition, I see no need for an infinite loop as that will either repeatedly roll and repeatedly square root, unless that is your goal.
Here is my code:

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? "))))

That is unless you want to repeatedly ask for user input In which case put the while loop above the creation of the User Input variable.

Edit: If you really do want re usability then use def to make this a function and have the following code

while True:
    play = input("Do you want to play? y/n")
    if play == "y":
        function_name()
    elif play == "n":
        break
Answered By: Professor_Joykill
# Python Program to calculate the square root

# Note: change this value for a different result
num = 8 

# To take the input from the user
#num = float(input('Enter a number: '))

num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
Answered By: JRG Prasanna
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.