Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我正试图编写一个python程序来查找素数_Python_Python 3.x - Fatal编程技术网

我正试图编写一个python程序来查找素数

我正试图编写一个python程序来查找素数,python,python-3.x,Python,Python 3.x,有很多方法可以做到这一点,但我想具体使用以下代码: """ Find the number is prime or not """ num =100 print(f"{num} is{' not a' if num%2==0 else 'not a' if num%x==0 else 'a' for x in range(3,(num//2)+1,2)} Prime Number") 我得到以下输出: 100 is<generator object <genexpr> at

有很多方法可以做到这一点,但我想具体使用以下代码:

"""
Find the number is prime or not
"""

num =100
print(f"{num} is{' not a' if num%2==0 else 'not a' if num%x==0 else 'a' for x in range(3,(num//2)+1,2)} Prime Number")
我得到以下输出:

100 is<generator object <genexpr> at 0x000001A5E440F0F8> Prime Number 
100是素数

您正在用
f-string
格式创建生成器对象

您可以使用
str
s
join
方法获取文本值 将
f-string
格式替换为:

print(f"{num} is{''.join({' not a' if num%2==0 else 'not a' if num%x==0 else 'a' for x in range(3,(num//2)+1,2)})}  Prime Number")
输出:

100 is not a  Prime Number

下面是错误:100是素数这不是错误,它是
print
语句的输出。@beer44这将打印出
a
,通常用于非素数。试试看
num=35
@unglish\u mark这就是他实现的逻辑。我的解决方案澄清了在
f-string
格式中从生成器对象获取值的问题。@beer44如果不想修复逻辑,为什么要添加集合,即
join({…})
而不是
join(…)
?有了集合,它似乎对某些数字有效,而没有集合,逻辑错误将是显而易见的。