简体   繁体   English

在 for 循环中断后打印

[英]Printing after a break in a for loop

I'm trying to figure out how to print the final line of code for this - whether it's a prime number or not.我试图弄清楚如何为此打印最后一行代码 - 无论它是否是素数。 I can't seem to get it to print with the code I have.我似乎无法使用我拥有的代码打印它。 Any help would be appreciated.任何帮助,将不胜感激。 Thanks!!谢谢!!

number = int(input("Enter a positive number to test: "))

while number <= 0:
    print ("Sorry, only positive numbers. Try again.")
    number = int(input("Enter a positive number to test: "))

test = 2

number1 = number - 1
for x in range (0, number1):
    trial = number % test
    if trial != 0:
        print (test, "is NOT a divisor of", number, "...")
        break
        print (number, "is a prime number!")
    else:
        print (test, "is a divisor of", number, "...")
        break
        print (number, "is not a prime number!")
    test = test + 1

The break statement ends the execution of the branch. break语句结束分支的执行。 The following print statement is never reached.永远不会达到以下print语句。

To get the correct functionaility use a boolean value and perform the check at the end:要获得正确的功能,请使用布尔值并在最后执行检查:

is_prime = True

for x in range (2, number):
    trial = number % x
    if trial != 0:
        print (x, "is NOT a divisor of", number, "...")
    else:
        is_prime = False
        print (x, "is a divisor of", number, "...")

if is_prime:
    print (number, "is a prime number!")
else:
    print (number, "is not a prime number!")

You also do not need to use a variable test .您也不需要使用变量test Use the x from your range directly.直接使用您范围内的x

Have a look at the Python reference for the keyword for more information.有关更多信息,请查看关键字的Python 参考

Syntax:句法:

if expression:

    statement(s)

else:

    statement(s)

It executes all statements with break so print will be never happen...它使用break执行所有语句,因此永远不会发生打印...

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

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