About bloggers : Former Internet manufacturer tencent staff , Network security giant Venustech staff , Alibaba cloud development community expert blogger , WeChat official account java Quality creators of basic notes ,csdn High quality creative bloggers , Entrepreneur , Knowledge sharers , Welcome to your attention , give the thumbs-up , Collection .
In the actual development process , You will often encounter many identical or very similar operations , At this time , Code that implements similar operations can be encapsulated as functions , Then call the function where you need it . This can not only realize code reuse , It can also make the code more organized , Increase code reliability . Now let's introduce python Goldbach conjecture, a typical case of function .
example : Goldbach conjectures : Each is not less than 6 Even numbers of are the sum of two odd primes , Writing program to verify Goldbach conjecture 20 Positive even numbers within are true . Copy to pycharm To view the , Very easy to understand .
def prime(i): # Defined function , Judge i Prime or not
if i<=1: # If less than or equal to 1, return 0(i Not primes )
return 0
if i==2: # If it is equal to 2, return 1(i Prime number )
return 1
for j in range(2,i): # Judge i Prime or not
if i%j==0: #i Can be j Divide up , Remainder is 0
return 0 # return 0,i Not primes
elif i!=j+1: # If i It's not equal to j+1, continue
continue
else:
return 1 # otherwise ,i be equal to j+1, return 1(i Prime number )
n=0
for i in range(6,21,2):
k=2
while k<=i/2:
j=i-k
flag1=prime(k) # call prime function
if flag1: # If k As a prime number
flag2=prime(j) # call prime function
if flag2: # If k and j All prime numbers
print(i,'=',k,'+',j) # Output results
n+=1
k=k+1
give the result as follows .
1、 Liao Xuefeng's official website
2、python Official website
3、Python Programming case tutorial
The above is about Python Goldbach conjecture and related knowledge , You can refer to it , If you think it's good , Welcome to thumb up 、 Collection 、 Looking at , Welcome to wechat search java Basic notes , Relevant knowledge will be continuously updated later , Make progress together .