不支持 / 的操作数类型:'str' 问题

问题描述

我的代码

a = input("Enter a number: ")
b = input("Enter another number: ")
int(a)
int(b)
if a == 0:
    print("You cannot divide a number by 0")
if b == 0:
    print("You cannot divide by 0")
else:
    print("The first number,",a,"divided by the second number,b,"equals",a / b)

错误

File "C:/Users/aaron/.PyCharmCE2019.3/config/scratches/scratch_1.py",line 10,in <module>
    print("The first number,a / b)
TypeError: unsupported operand type(s) for /: 'str' and 'str'

我已将其转换为整数(显然不是,但我认为我已转换!)但想知道我错在哪里。

解决方法

通过查看我认为的错误,您试图将两个字符串分开。

如果变量 a 和 b 作为输入而不是硬编码,请尝试使用:

# to take the input 
a = int(input())
b = int(input())

如果您对 a 和 b 的值进行硬编码,请避免使用单引号或双引号。 使用引号使变量成为字符串。

a = '12' # is a string and you can't perform division operation on this
a = 12 # is an integer

您还可以通过以下方式将字符串转换为整数:

a = int(a) # If initially variable a is a string
print("The first number,",a,"divided by the second number,b,"equals",a / b)

如果 a 和 b 都是整数或浮点数,这应该有效。

,

尝试 10


print("The first number,int(a) / int(b))

a = int(input("Enter a number: "))
b = int(input("Enter another number: "))

如果您想了解更多信息,请查看:

Asking the user for input until they give a valid response

,
int(a)/int(b)

a=int(a)
b=int(b)
and str(a) and str(b) in the text 
,

这里的问题是您试图分割 2 个字符串。这是不可能的,因为您不能分割文本。您首先必须将它们转换为整数或浮点数等数字。

您尝试这样做:

int(a)
int(b)

但是,这并不是将变量从字符串转换为整数,因为您没有将 int() 函数的结果分配给变量。

基本上,int() 函数正在返回一个刚刚丢失的值。

您可以改为这样做:

a = int(a)
a = int(b)

如果你愿意,你可以用更少的行来完成:

a = int(input("Enter a number: "))
b = int(input("Enter another number: "))