简体   繁体   中英

If Statements in IDLE python3.9 Not Functioning Properly

Screenshot of Issue

I'm trying to learn python and was trying out simple if statements in IDLE that comes with the python3.9 installation for macOS Catalina 10.15.7.

I am following along with the beginner guide on Python's own website ( https://docs.python.org/3.9/tutorial/controlflow.html ) and for some reason the IDLE shell will not allow me to write an elif condition. Whenever I write the first if statement, hit enter, type the code for that condition, and hit enter again, it skips me to the next line and if I try to type and elif or else condition, it gives me a syntax error when I hit enter to go to the next line. I've tried looking this up but, I can't find any information or anyone with similar experiences.

My text looks like this...

x = int(input("Please enter an integer: "))

-enter integer-

if x < 0:

x = 0
print('Negative changed to zero'`

Here it goes to a new line and I type...

elif x == 0:

and I get an error that just says invalid syntax even though it's forcing me to a new line. Not sure what to do but would appreciate any tips or advice on the issue.

You are almost there. Your indentation for the elif is wrong. Python is very particular about the indentation. You are currently doing:

if x < 0:
    x = 0
    print('Negative changed to zero')
    elif x == 0:
    print('Zero')

Instead you should do:

if x < 0:
    x = 0
    print('Negative changed to zero')
elif x == 0:
    print('Zero')

You aren't "out-denting" properly. Instead of hitting a full return for the elif, you have to backspace over your indent, and continue from there. Once you get the >>> prompt, your if statement is closed out; you can't add any elif or else clause any more. Your session should look something like this:

>>> x = 2
>>> if x < 0:
    x = 0
    print("TRUE")
elif x == 0:
    print("ELIF")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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