只想要一些关于我的素数发生器的反馈.例如,它是否正常,它是否用于很多资源等.它不使用库,它相当简单,它反映了我目前的编程技巧状态,所以不要因为我想学习而退缩.
def prime_gen(n):
primes = [2]
a = 2
while a < n:
counter = 0
for i in primes:
if a % i == 0:
counter += 1
if counter == 0:
primes.append(a)
else:
counter = 0
a = a + 1
print primes
Run Code Online (Sandbox Code Playgroud) 我一直在经历Automatetheboringstuff,并遇到了一个名为逗号代码的挑战(第4章末).你必须编写一个函数,它接受一个列表并打印出一个字符串,用逗号连接元素并在最后一个元素之前添加"和".
请记住,我对python很新,或为此编程,它仍然是一个可管理的任务,但输出在插入"和"之前有一个逗号.所以我修改了代码来清理它.这是我的代码:
def comma_separator(someList):
"""The function comma_separator takes a list and joins it
into a string with (", ") and adds " and " before the last value."""
if type(someList) is list and bool(someList) is True:
return ", ".join(someList[:-1]) + " and " + someList[-1]
else:
print("Pass a non-empty list as the argument.")
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?有没有可以做到这一点的模块?