【问题标题】:Python - Can't convert int to str implicity in this specific code [duplicate]Python - 无法在此特定代码中将 int 隐式转换为 str [重复]
【发布时间】:2023-03-21 03:00:02
【问题描述】:

我有一个 GCSE 问题,Python 要求我在一个函数中输入三个数字并打印最大的一个。

我的问题是,它显示错误Can't convert int to str implicity

inputed_1 = int(input("Give me a number: "))
inputed_2 = int(input("Give me another number: "))
inputed_3 = int(input("Give me another number: "))

def largest(num1, num2, num3):
   if num1 > num2 and num1 > num3:
      print("Your first number was the largest: " + num1)
   elif num2 > num1 and num2 > num3:
      print("Your second number was the largest: " + num2)
   elif num3 > num1 and num3 > num2:
      print("Your third number was the largest: " + num3)

largest(inputed_1, inputed_2, inputed_3)

【问题讨论】:

    标签: python implicit-conversion


    【解决方案1】:

    在连接之前尝试将整数转换为字符串:

    print("Your first number was the largest: " + str(num1))
    

    【讨论】:

    • 如果我这样做,我认为我无法在控制流中比较它们。
    • 哦对了,误会你说的对不起
    • 我更喜欢的替代方法是print("Your first number was the largest: {}".format(num1))(如果必须的话,使用% 的旧形式)。在这种情况下,它可能无关紧要,但您可以在 {} 中使用各种格式修饰符,这在处理浮点等时很好......
    猜你喜欢
    • 2015-03-23
    • 2013-09-27
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2017-12-21
    • 1970-01-01
    相关资源
    最近更新 更多