Home  >  Article  >  Backend Development  >  Python outputs prime numbers between 2 and 100

Python outputs prime numbers between 2 and 100

王林
王林Original
2020-05-06 11:25:4216688browse

Python outputs prime numbers between 2 and 100

Purpose:

Calculate the number of prime numbers between 2-100 and return the result

What are prime numbers?

Prime numbers refer to natural numbers greater than 1 that have no other factors except 1 and itself.

Code implementation:

# 定义一个列表接受返回的质数
list_num = []

def primeNum(n, m):
    # 遍历n-m(含nm)间的所有数字并赋值给i
    for i in range(n, m + 1):
        # 遍历2-i中的数并赋值给x
        for x in range(2, i):
            # 判断i能否被x取整,能取整说明能被整除,跳出for循环
            if i % x == 0:
                break
        # 不能取整说明是质数添加到里列表list_num中
        # 这里用到了for else,需要注意一下
        else:
            list_num.append(i)

primeNum(2, 100)
print('您输入的区间中质数的个数为'+str(len(list_num))+'\n它们是:'+str(list_num))

The result is as shown:

Python outputs prime numbers between 2 and 100

##Recommended tutorial:

python tutorial

The above is the detailed content of Python outputs prime numbers between 2 and 100. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn