【问题标题】:how can i return a changing int within a string in python?如何在 python 的字符串中返回一个不断变化的 int?
【发布时间】:2014-10-30 04:24:53
【问题描述】:

我正在处理的函数应该告诉用户他们给出的数字是否是完美数字(即等于其因子总和的一半)。如果用户给出数字 8,则输出应如下所示:

8 is not a perfect number

但我不知道要在 return 语句中放入什么来使 int(根据用户输入而变化)与字符串一起打印出来。到目前为止的代码如下所示:

#代码在另一个更大的函数中,这就是 elif 的原因

 elif(message == 2):
    num1 = int(input("""Please enter a positive integer :"""))
    while(num1 <= 0):
        print("Number not acceptable")
        num1 = int(input("""Please enter a positive integer :"""))
    thisNum = isPerfect(num1)
    if(thisNum == True):
        return num1, is a perfect number
    elif(thisNum == False):
        return num1 is not a perfect number

def isPerfect(num1):
    sumOfDivisors = 0
    i = 0
    listOfDivisors = getFactors(num1)
    for i in range(0, len(listOfDivisors) - 1):
        sumOfDivisors = sumOfDivisors + listOfDivisors[i]
        i += 1
    if(sumOfDivisors / 2 == num1):
        return True
    else:
        return False

如果我要返回(num1,“不是一个完美的数字”)它会像 (8, '不是一个完美的数字')

【问题讨论】:

  • return '{} is not a perfect number'.format(num1)
  • 顺便说一下,你的求和操作是错误的。您从 0 - len(listOfDivisors) - 1 迭代,但每次在循环内递增 i,使 i 在每次通过时增加 2。考虑使用sum 函数,例如sumOfDivisors = sum(getFactors(num1))

标签: python string int return-value


【解决方案1】:
return "%d is not a perfect number" % number

您可以使用 %s 对字符串进行格式化。无论如何,还有一些其他方法,如String Formating Operators 所述

【讨论】:

    【解决方案2】:

    将整数转换为字符串并连接语句的其余部分:

    return str(num1) + ' is not a perfect number'
    

    【讨论】:

      【解决方案3】:

      您可以使用.format() 迷你语言,同时简化您的代码:

       elif(message == 2):
          num1 = int(input("""Please enter a positive integer :"""))
          while(num1 <= 0):
              print("Number not acceptable")
              num1 = int(input("""Please enter a positive integer :"""))
          if isPerfect(num1):
              return '{} is a perfect number'.format(num1)
          else:
              return '{} is not a perfect number'.format(num1)
      

      同样在您的其他方法中,只需返回比较结果:

      def isPerfect(num1):
          sumOfDivisors = 0
          listOfDivisors = getFactors(num1)
          for i listOfDivisors:
              sumOfDivisors += i
          #if(sumOfDivisors / 2 == num1):
          #    return True
          #else:
          #    return False
          return sumOfDivisors / 2 == num1
      

      另外,我建议阅读PEP-8,这是 Python 的样式指南。

      【讨论】:

        猜你喜欢
        • 2014-05-23
        • 1970-01-01
        • 2021-11-22
        • 2022-01-20
        • 2021-08-23
        • 1970-01-01
        • 2015-10-26
        • 2015-04-17
        • 1970-01-01
        相关资源
        最近更新 更多