Common_Codin
Common_Codin

Reputation: 143

How to split a user input coordinate and use in calculations?

I am trying to calculate the radius of a circle using 2 points given by the user.
The program works with a simple single integer entry like this ...

x1 = int(input("enter x1"))
y1 = int(input("enter y1"))

But I wanted to write the input in a way that allows the user to enter a point like this...

2,5

Below is the code for the program, it will accept the user
input of x1,y1 and x2,y2, but the calculations are coming out as 0.0.

What am I missing?

import math

def distance (x1,y1,x2,y2):
    dis = math.sqrt((x2-x1)**2 + (y2-y1)**2)
    return distance

def radius (x1,y1,x2,y2):
    rad = distance(x1,y1,x2,y2)
    return rad

def main():

coordinate_1 = input("enter x1 and y1")
    coordinate_1 = coordinate_1.split(",") 
    x1 = int(coordinate_1[0])
    y1 = int(coordinate_1[1])

    coordinate_2 = input("enter x2 and y2")
    coordinate_2 = coordinate_2.split(",") 
    x2 = int(coordinate_1[0])
    y2 = int(coordinate_1[1])

    rad = radius(x1,y1,x2,y2)

    print("the radius is:", rad)

main()

Upvotes: 0

Views: 279

Answers (2)

Harris Irfan
Harris Irfan

Reputation: 218

You have not shared complete working code, but if you're having an output of 0.0, it is because of the following lines of code:

x2 = int(coordinate_1[0])
y2 = int(coordinate_1[1])

You are using the first input coordinate for x2 and y2, and so the distance between them results to be 0.0.

You ought to update the above lines to:

x2 = int(coordinate_2[0])
y2 = int(coordinate_2[1])

Below I have shared complete code with modifications and after resolving errors (on your original code), that works:

import math

def calc_distance(x1,y1,x2,y2):
    dis = math.sqrt((x2-x1)**2 + (y2-y1)**2)
    return dis

def calc_radius(x1,y1,x2,y2):
    rad = calc_distance(x1,y1,x2,y2)
    return rad

coordinate_1 = eval(input("enter x1 and y1"))
x1 = int(coordinate_1[0])
y1 = int(coordinate_1[1])

print(x1, y1)

coordinate_2 = eval(input("enter x2 and y2"))
x2 = int(coordinate_2[0])
y2 = int(coordinate_2[1])

radius = calc_radius(x1, y1, x2, y2)

print("the radius is:", radius)

Upvotes: 1

DevScheffer
DevScheffer

Reputation: 499

You can use like that to get a list of the coordinate

input1='2,5'
a = input1.split(',')
a=list(map(int,a))
print(a)
# [2, 5]

Upvotes: 1

Related Questions