【问题标题】:TypeError: unsupported operand type(s) for -: 'str' and 'str' in python [duplicate]TypeError:不支持的操作数类型-:python中的“str”和“str”[重复]
【发布时间】:2018-12-04 09:14:14
【问题描述】:

我编写了这个简单的脚本,但是当它进入数学部分时它给了我一个错误。我尝试将其设置为 int(),但这也不起作用。

import os
from fractions import Fraction
def cls():
    os.system('cls' if os.name=='nt' else 'clear')
def pause():
    programPause = raw_input("Press the <ENTER> key to continue...")

def header():
    print("Slope Calculator")
    print("Daniel Meskin")
    print("BSD Licen    ce")
    print("<------------------    >")

header()
x1 = input("(")
gcoord="("+x1+","
cls()
header()
y1 = input(gcoord)
gcoord="("+x1+","+y1+"),("
cls()
header()
x2 =input(gcoord)
gcoord="("+x1+","+y1+"),("+x2+","
cls()
header()
y2 = input(gcoord)
gcoord="("+x1+","+y1+"),("+x2+","+y2+")"
cls()
header()
print(gcoord)
slope = (y2-y1)/(x2-x1)
slopef=Fraction(slope)
print(slope+"|"+slopef)
pause()

编辑:我意识到我的错误,很抱歉造成混乱:(

【问题讨论】:

  • input 返回一个str,必须将其转换为int。函数int() 可以接受一个字符串并返回整数。

标签: python


【解决方案1】:

您需要将str转换为数字类型才能对它们进行-操作:

slope = (float(y2)-float(y1))/(float(x2)-float(x1))

(或者你可以使用int()而不是float(),这取决于你的需求)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-20
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 2018-04-22
    • 2013-08-18
    相关资源
    最近更新 更多