[英]How can I accept negative values as the inputs in Python?
如何接受负值作为输入?
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)
谢谢。
我假设您正在输入诸如1 -42 14
或类似的输入。 input()
返回一个字符串。 当您执行[int(x) for x in x_coordinates]
时,您正在对字符串中的每个字符调用int()
。 因此,您应该首先在空格上.split()
字符串,然后在每个成员上调用int()
:
x_coordinates = [int(x) for x in x_coordinates.split()]
鉴于上述输入,这将返回
[1, -42, 14]
input
给你一个字符串,当你迭代它时,你会分别得到每个字符。 想出一个分隔符,比如空格,然后分割输入:
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)
然后:
robert@here:~$ python mcve.py
Enter the x coordinates: 1 2 3
Enter the y coordinates: -1 -2 -3
2.8284271247461903
也就是说,如果您只想读取 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)
或者至少检查输入了多少数字并打印错误。
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.