我在练习python练习4

2024-04-26 05:12:01 发布

您现在位置:Python中文网/ 问答频道 /正文

number = int(raw_input("Enter a number :"))
div = range(0, number)
list = []
while div <= number:
    if number % div == 0: 
        list.append(div)
        div =+ 1

    print list

这是我为这个练习编写的代码: http://www.practicepython.org/exercise/2014/02/26/04-divisors.html 我是新的编程,所以我不知道我的代码有什么问题,但它没有给出任何输出。你知道吗


Tags: 代码divhttpnumberinputrawifwww
2条回答

以下是您需要的代码:

number = int(input("Enter a number :"))
list = []
# theoretically this is the limit you should test for divisors
for div in range(2, int(number/2 + 1)):
    if number % div == 0:
        # adds the divisor to the list
        list.append(div)
        div += 1

# prints all divisors in new line
for item in list:
    print(item)

如果您使用的是python2.7,请使用input而不是raw_input

我想这个答案很简单,从投票结果来看,人们也这么认为。然而。。。只有通过提问才能学习!你知道吗

您所建议的代码中有三个基本错误,以及一些使其更具python风格的方法。你知道吗

  1. 首先,也是最重要的,被零除是不可能的!所以您需要检查范围(1-number)内的数字。你知道吗
  2. 基于缩进list被多次打印,而不是只在while循环结束时打印。你知道吗
  3. 您希望避免使用list作为变量,因为它是Python关键字。你知道吗

那么,为了让它更具python风格,我的建议是:

number = int(input("Enter a number :"))
output = []

for i in range(1,number+1):
  if not number%i:
    output.append(i)

print(output)

请注意,raw_input在python3.x中已经不存在了。还请注意,通过这种方式,我们避免了while循环,因为经验很容易导致错误。取而代之的是自动循环通过range(1,number)生成的列表中的条目。你知道吗

最后是关于range的注释,但也可能是关于语义的。我认为number也是number的除数。为此,我使用了range(1,number+1)。因为,例如range(5)返回一个到5[0,1,2,3,4]的列表。也就是说,它不包括5。你知道吗

相关问题 更多 >