[英]How can I accept negative values as the inputs in Python?
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.我假设您正在输入诸如
1 -42 14
或类似的输入。 input()
returns a string. input()
返回一个字符串。 When you do [int(x) for x in x_coordinates]
, you are calling int()
on each character in the string.当您执行
[int(x) for x in x_coordinates]
时,您正在对字符串中的每个字符调用int()
。 So, you should .split()
the string on spaces first, then call int()
on each member:因此,您应该首先在空格上
.split()
字符串,然后在每个成员上调用int()
:
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. input
给你一个字符串,当你迭代它时,你会分别得到每个字符。 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.也就是说,如果您只想读取 2 x 和 2 y 值,您可能应该只使用单独的变量。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.