How can I accept negative values as the inputs?
import math
x_coordinates = input("Enter the x coordinates: ")
y_coordinates = input("Enter the y coordinates: ")
x_coordinates = [int(x) for x in x_coordinates]
y_coordinates = [int(x) for x in y_coordinates]
total_x = (x_coordinates[-1] - x_coordinates[0]) ** 2
total_y = (y_coordinates[-1] - y_coordinates[0]) ** 2
total = total_x + total_y
total = math.sqrt(total)
print(total)
Thanks.
I assume you're entering input such as 1 -42 14
or something similar. input()
returns a string. When you do [int(x) for x in x_coordinates]
, you are calling int()
on each character in the string. So, you should .split()
the string on spaces first, then call int()
on each member:
x_coordinates = [int(x) for x in x_coordinates.split()]
Given the above input, this would return
[1, -42, 14]
input
gives you one string, and when you iterate over that, you get each character separately. Come up with a separator character, like space, and split the inputs on that:
import math
x_coordinates = input("Enter the x coordinates: ")
y_coordinates = input("Enter the y coordinates: ")
x_coordinates = [int(x) for x in x_coordinates.split(" ")]
y_coordinates = [int(x) for x in y_coordinates.split(" ")]
total_x = (x_coordinates[-1] - x_coordinates[0]) ** 2
total_y = (y_coordinates[-1] - y_coordinates[0]) ** 2
total = total_x + total_y
total = math.sqrt(total)
print(total)
Then:
robert@here:~$ python mcve.py
Enter the x coordinates: 1 2 3
Enter the y coordinates: -1 -2 -3
2.8284271247461903
That said, if you only want to read 2 x and 2 y values anyway, you should probably just use separate variables.
import math
x1 = int(input("Enter x1: "))
x2 = int(input("Enter x2: "))
y1 = int(input("Enter y1: "))
y2 = int(input("Enter y1: "))
total_x = (x2 - x1) ** 2
total_y = (y2 - y1) ** 2
total = total_x + total_y
total = math.sqrt(total)
print(total)
Or at least check how many numbers are entered and print an error.
import math
x_coordinates = input("Enter the x coordinates: ")
y_coordinates = input("Enter the y coordinates: ")
x_coordinates = [int(x) for x in x_coordinates.split(" ")]
y_coordinates = [int(x) for x in y_coordinates.split(" ")]
if len(x_coordinates) > 2 or len(y_coordinates) > 2:
print("Need 2 x and y coordinates")
else:
total_x = (x_coordinates[-1] - x_coordinates[0]) ** 2
total_y = (y_coordinates[-1] - y_coordinates[0]) ** 2
total = total_x + total_y
total = math.sqrt(total)
print(total)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.