简体   繁体   English

为什么Python在这里打印出多个值?

[英]Why is Python Printing out multiple values here?

I am writing this function to test the primality of numbers, I know that it is not the best code but I would wish it prints out Not prime when a number is not prime and Is prime when a number is prime. 我写这个函数测试数的素性,我知道这是不是最好的代码,但我会希望它打印出不是素数 ,当数不是素数和为素数 ,当数是素数。 The problem is that it prints out Not prime then Is prime for numbers that are not prime... For example this code: 问题在于,对于不是素 的数字,它会打印出不是素数,然后是素数。例如,以下代码:

def isPrime(n):
  for i in range(2, n):
    if n%i==0:
        print "Not Prime!"
        break
  print "Is Prime"

isPrime(5)
isPrime(18)
isPrime(11)

Prints out. 打印出来。

Is Prime
Not Prime!
Is Prime
Is Prime

Help me out, What should I do? 帮帮我,我该怎么办? I am a beginner. 我是初学者。

break doesn't exist out of a function -- it just exits a loop. break不存在于函数之外,它只是退出循环。 So as soon as you print "Not prime", you exit the loop and move on to the next print statement. 因此,只要您打印“ Not prime”,就退出循环并转到下一个打印语句。

replace the break with the keyword return instead. 用关键字return代替break return will immediately exit the function, returning the value you give the return statement, or None if you just put return with no value next to it. return将立即退出函数,返回你给return语句,或者值None ,如果你只是把return ,没有它旁边的值。

Here is a fix (python 3) 这是一个修复程序(python 3)


def isPrime(n):
  prime = True
  for i in range(2, n):
    if n%i==0:
        print("Not Prime!")
        prime = False
        break
  if prime:
      print("Is Prime") 

isPrime(5)
isPrime(18)
isPrime(11)

The problem in the code you posted is that the last print is always executed. 您发布的代码中的问题是,总是执行最后一次print

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM