如何找到一定数量的因子,只显示一行中的输出

问题描述 投票:1回答:4

在这里,我得到了这样的代码:

x=int(input("Enter number: "))
for i in range(1,x+1):
    if x%i==0:
        print("Factors are",i)

我希望输出看起来像这样......

Enter number: 10 ↵ 
Factors are 1 2 5 10 

但事实证明是这样的

Enter number: 10
Factors are 1
Factors are 2
Factors are 5
Factors are 10

PS。我被困在这里2天,我真的需要帮助!

python-3.x
4个回答
0
投票
x=int(input("Enter number: "))
factors = []
for i in range(1,x+1):
    if x%i==0:
        factors.append(str(i))

if factors:
    print("Factors are", ", ".join(factors))

0
投票

您可以使用生成器表达式并将其输出解压缩为print的参数:

x = int(input('Enter number: '))
print('Factors are', *(i for i in range(1, x + 1) if x % i == 0))

0
投票

在print中使用end =“”将确定在语句后打印的内容。默认情况下,'print()'函数以换行符结尾。

x=int(input("Enter number: "))

print("Factors are",end= " ") # function print ends with a space

for i in range(1,x+1):
   if x%i==0:
     print(i,end=" ")

0
投票

你可以使用过滤器:

x = int(input("Enter number: "))

factors = filter(lambda i: not x % i, range(1, x + 1))

print("Factors are: ", factors)

或者更好的理解:

x = int(input("Enter number: "))

factors = (i for i in range(1, x + 1) if not x % i)

print("Factors are: ", *factors)
© www.soinside.com 2019 - 2024. All rights reserved.