0

My programme has a runtime error, but I couldn't figure it out. Where's the problem? It would be much appreciated if you could help me! :) Here's the code:

P.S. I'm kinda new to python! Thanks for your help!

import math
n = input()
for a in range(n):
    x, y = input().split()
    num = math.sqrt(x**2+y**2)
print(num)
2
  • 3
    what's the error? Please post full traceback. Commented Aug 19, 2020 at 4:39
  • 1
    n is string and not integer. So range(n) would not work. You have to convert n to integer first Commented Aug 19, 2020 at 4:44

2 Answers 2

0

The function input() returns a string. The function split() returns a list of strings. You cannot do any mathematical operation using strings. You have to cast to the correct type before performing any operation.

Try:

import math
n = input()
for a in range(int(n)):
    x, y = input().split()
    x, y = float(x), float(y) # for example, it can be int as well
    num = math.sqrt(x**2+y**2)
    print(num)
Sign up to request clarification or add additional context in comments.

4 Comments

I know your answer is accepted and all but your code doesn't work.
@hrokr, why doesn't it work?
@hrok I tested here and it works. What error are you getting?
Same error with a straight copy/paste of all the code into repl.it
0

You have at least two errors.

The first is your input is left as a string. You should convert it by using n = int(input()) or n = float(input())

The second is you have a runtime error: ValueError: not enough values to unpack (expected 2, got 1) which is resulting from your input. You're trying to pack that input into two separate values. But, again, you only have one.

I think what you are looking for is more like this:

import math
x = float(input())
y = float(input())

num = math.sqrt(x**2+y**2)
print(num)

but this could be further shortened to:

x = float(input())
y = float(input())

print((x**2+y**2)**.5)

3 Comments

n is string (in python3). Why you are converting it to string again? That does not help at all. Also if inside for loop if input is values separated by space, the 2nd problem you mentioned would not occur
Well, it's tough to do math operations on strings. And we can tell he's looking to do the Pythagorean theorem. The rest is because he's new, which he clearly states.
But, also because he's new, he accepted an answer without actually checking that it works. So, there's that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.