SyntaxError: invalid syntax for breaking a true while and print a cod

74 views Asked by At

I want to print the "bye" after breaking the True while, but I'm having trouble. Here is my code

while (True) :
    number = (input("pleas enter a number : \n"))
    if number == ("don") :
          break and print("bye") 
    else: 
        number = int(number)
        if number%2 == 0 :
            print("even")
        else :
            print("Odd")

and this is the ful error:

line 4
    print("bye") and break   
                   ^^^^^   
SyntaxError: invalid syntax

All this code is to distinguish even and odd numbers received from the user. My goal was to write an true while to receive an infinite number of numbers from the user, and when the user uses the "don" command, this loop end and show the "bye" message to the user. But this code encountered an error and the program did not run

2

There are 2 answers

0
Chris On

break is not an expression and cannot appear as an operand to and. Instead write those two steps explicitly.

Also, you can remove a lot of unnecessary parens from your code.

while True:
    number = input("please enter a number : \n")
    if number == "don":
        print("bye")
        break
    else: 
        number = int(number)
        if number % 2 == 0:
            print("even")
        else:
            print("Odd")

And since int(number) is only called once and it's value is never needed again afterwards:

while True:
    number = input("please enter a number : \n")
    if number == "don":
        print("bye")
        break
    elif int(number) % 2 == 0:
        print("even")
    else:
        print("Odd")
0
Barmar On

break is a statement, not an expression, so you can't combine it with something else using and.

To do two things in an if, put them on separate lines.

    if number == "don":
        print("bye")
        break