0

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 
3
  • 1
    You carefully check if the input could be converted to a number, then don't actually bother to do that! Commented Mar 21, 2017 at 6:36
  • Also, numbers like 1.5 or 1E10 will not be valid - why? The pythonic way would be to try converting the input to a float and to print the error message only when an exception occurs. Commented Mar 21, 2017 at 7:12
  • Possible duplicate of TypeError: unsupported operand type(s) for -: 'str' and 'int' Commented Mar 21, 2017 at 7:16

3 Answers 3

3

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.')
Sign up to request clarification or add additional context in comments.

Comments

0

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.')

Then, his second line will fail.
Hmm, I tried it and it ruled out that error. However, I am now give another error message: Traceback (most recent call last): File "/Users/username/Documents/Coding/squareroot.py", line 3, in <module> if len(num) > 0 and num.isdigit(): TypeError: object of type 'int' has no len()
@ShivkumarKondi What is the difference between my answer and yours?
@eyllanesc I just did parsing in first attempt and encounter isdigit problem. You can see the difference. I have executed and then updated my code.
In the original question, that task is already in place, I do not put it for that. I still see you copied my answer.
0

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.')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.