【问题标题】:TypeError: unsupported operand type(s) for &: 'str' and 'int' in Python [duplicate]TypeError:&不支持的操作数类型:Python中的“str”和“int”[重复]
【发布时间】:2020-07-06 08:20:49
【问题描述】:

当我尝试运行此代码时,标题中不断出现错误。我认为问题在于变量不是整数,但这并没有解决问题。代码如下:

shoeSize=int(input("Please enter your shoe size."))
ageOne=int(input("Please enter your age."))

if ageOne >= 18:
    print("Your membership fee is £" & shoeSize*10)
elif ageOne <= 65:
        print("Your membership fee is £" & shoeSize*5)
else:
        print ("You cannot join!")

【问题讨论】:

  • &amp;?查看字符串插值。

标签: python


【解决方案1】:

您可以使用&amp; 进行字符串连接,例如Visual Basic,但它是 Python 中的按位与运算符。

格式化字符串的最现代(也是最简单的)方法是将它们设为“f-strings”:

shoeSize = int(input("Please enter your shoe size."))
ageOne = int(input("Please enter your age."))

if ageOne >= 18:
    print(f"Your membership fee is £{shoeSize*10}")
elif ageOne <= 65:
    print(f"Your membership fee is £{shoeSize*5}")
else:
    print("You cannot join!")

【讨论】:

    【解决方案2】:

    好像是语法错误的问题:

    if ageOne >= 18:
        print("Your membership fee is £" & shoeSize*10)
                                         ^
    
    elif ageOne <= 65:
            print("Your membership fee is £" & shoeSize*5)
                                             ^
    

    您可以改用,

    if ageOne >= 18:
        print("Your membership fee is £", shoeSize*10)
                                        ^
    
    elif ageOne <= 65:
            print("Your membership fee is £", shoeSize*5)
                                            ^
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-15
      • 2012-11-29
      • 2012-12-31
      • 1970-01-01
      相关资源
      最近更新 更多