1

I need to create a script that calculates the distance between two coordinates. The issue I'm having though is when I assign the coordinate to object one, it is stored as a string and am unable to convert it to a list or integer/float. How can I convert this into either a list or integer/float? The script and error I get is below.


Script:

one=input("Enter an x,y coordinate.")
Enter an x,y coordinate. 1,7

int(1,7)

Traceback (most recent call last):

  File "<ipython-input-76-67de81c91c02>", line 1, in <module>
    int(1,7)
  TypeError: int() can't convert non-string with explicit base
bhansa
  • 7,282
  • 3
  • 30
  • 55
k.smith
  • 41
  • 2
  • 4
    `x,y = map(int, input("Enter an x,y coordinate.").split(","))` ? – Nir Alfasi Sep 03 '17 at 19:17
  • Python docs are great. So [`int()`](https://docs.python.org/3/library/functions.html#int) is a built in function which when 2 arguments are given, the second argument is the base. – tread Sep 03 '17 at 19:20

3 Answers3

2

You have to convert the entered string to int/float by first splitting the string into the point components, then casting to the appropriate type:

x, y = map(float, one.split(','))

To keep the entered values as a single custom datatype, named Point for example, you can use a namedtuple:

from collections import namedtuple

Point = namedtuple('Point', 'x, y')

Demo:

>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'x, y')
>>> Point(*map(float, '1, 2'.split(',')))
Point(x=1.0, y=2.0)
>>> _.x, _.y
(1.0, 2.0)
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
0

Convert the input into the specific type as int or float

Into a list:

_list = list(map(int, input("Enter an x,y coordinate.").split(",")))

or into variables:

a, b = map(int, input("Enter an x,y coordinate.").split(","))
bhansa
  • 7,282
  • 3
  • 30
  • 55
0

After this one=input("Enter an x,y coordinate.") the variable one contains a string that looks like this 'x, y' which cannot be converted to int as is.

You need to first split the string using str.split(',') which will yield a list [x,y] then you can iterate through the list and convert each of x and y to int using map which applies the int(..) function to every element of the list [x, y].

In code, you can do it as follows:

one=input("Enter an x,y coordinate.")
x, y = map(int, one.split(','))

As a side note, you should consider wrapping the user input with a try .. except clause to handle the case where a user inserts non-int input:

try: 
    one=input("Enter an x,y coordinate.")
    x, y = map(int, one.split(','))
except Exception as e: 
    print("Please provide a valid input")
Mohamed Ali JAMAOUI
  • 14,275
  • 14
  • 73
  • 117