如何编辑此代码以使其输出类似"在你的范围内的素数是:11、13、17、19、23和29;如果边界是10和30?
lower = int(input("Input lower bound"))
upper = int(input("Input upper bound"))
print("The prime number(s) in your range are:", end = " ")
for num in range(lower, upper+1):
if(num>1):
for i in range(2,num):
if(num%i)==0:
break
else:
print(num, end = ", ")
将它们存储在列表中并在末尾打印,使用sep参数提及分隔,使用end提及末尾。
lower = int(input("Input lower bound"))
upper = int(input("Input upper bound"))
print("The prime number(s) in your range are:", end = " ")
primenums = []
for num in range(lower, upper+1):
if(num>1):
for i in range(2,num):
if(num%i)==0:
break
else:
primenums.append(num)
if len(primenums) > 2:
print(*primenums[:-1] ,sep = ", ",end=" and ")
print(prime[-1])
else:
# if len(primenums) is 1 sep will be ignonred
print(*primenums,sep=" and ")
将素数存储在列表中。
primes = []
for num in range(lower, upper+1):
if(num>1):
for i in range(2,num):
if(num%i)==0:
break
else:
primes.append(num)
然后,在打印前将其格式化为字符串:
if len(primes) <= 2:
msg = " and ".join(str(p) for p in primes)
else:
msg = f"{', '.join(str(p) for p in primes[:-1])}, and {primes[-1]}"
print(f"The prime number(s) in your range are: {msg}")
", ".join(...)
使用字符串", "
连接迭代器中传递给它的所有元素。迭代器是str(p) for p in primes[:-1]
。此迭代器将primes
中除最后一个元素外的所有元素转换为要与", "
连接的字符串。f"..."
构造被称为f-string,是我在python中首选的字符串插值方式。
您可以这样做:
lower = int(input("Input lower bound: "))
upper = int(input("Input upper bound: "))
prime_numbers = list()
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
prime_numbers.append(str(num))
prepend = "The prime number(s) in your range are:"
if len(prime_numbers) > 2:
print(f"{prepend} {', '.join(prime_numbers[:-1])} and {prime_numbers[-1]}.")
else:
print(f"{prepend} {' and '.join(prime_numbers)}.")
这将输出:
Input lower bound: 3
Input upper bound: 10
The prime number(s) in your range are: 3, 5 and 7.
Input lower bound: 7
Input upper bound: 11
The prime number(s) in your range are: 7 and 11.
Input lower bound: 8
Input upper bound: 11
The prime number(s) in your range are: 11.
你可以添加范围内没有数字的特殊情况(如果需要(,比如:
elif prime_numbers:
print(f"{prepend} {' and '.join(prime_numbers)}.")
else:
print(f"No prime numbers found in range.")