簡體   English   中英

如何接受負值作為 Python 中的輸入?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM