rocketsnstuff
rocketsnstuff

Reputation: 103

Python Square Root Calculator Error

I wanted to make a simple square root calculator.

num = input('Enter a number and hit enter: ')

if len(num) > 0 and num.isdigit():
    new = (num**0.5)
    print(new)
else:
    print('You did not enter a valid number.')

It doesn't seem as if I have done anything wrong, however, when I attempt to run the program and after I have input a number, I am confronted with the following error message:

Traceback (most recent call last):
File "/Users/username/Documents/Coding/squareroot.py", line 4, in <module>
new = (num**0.5)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'float'

Process finished with exit code 1 

Upvotes: 0

Views: 575

Answers (3)

Dheeraj
Dheeraj

Reputation: 1202

Use Math module for simple calculations. refer: Math module Documentation.

import math
num = raw_input('Enter a number and hit enter: ')

if num.isdigit():
    num = float(num)
    new = math.sqrt(num)
    print(new)
else:
    print('You did not enter a valid number.')

Upvotes: 0

Ashish
Ashish

Reputation: 4330

You can use this solution. Here try and catch is capable of handling all kinds of input. So your program will never fail. And since the input is being converted to float. You won't face any type related error.

try:
    num = float(input('Enter a positive number and hit enter: '))
    if num >= 0:
        new = (num**0.5)
    print(new)

except:
    print('You did not enter a valid number.')

Upvotes: 3

Shivkumar kondi
Shivkumar kondi

Reputation: 6792

Input function returns you string value. so you need to parse it properly

num = raw_input('Enter a number and hit enter: ')

if num.isdigit():
  if int(num) > 0:
      new = (int(num)**0.5)
      print(new)
else:
    print('You did not enter a valid number.')

Upvotes: 0

Related Questions