lundi 30 mai 2016

Python: Do I have to use else statements (unless mandated by code)?

I know of if, else and elif statements and frequently see all three of them used in others' code. However, this is contradictory to the way I use them, and I would like to know which would be a better practice. The main reason I'm concerned is because I recently learned that else statements can also be used in loops, even without if statements (like, in case there's an error).

# Other's code:

select = input("Enter 'a' to add, 's' to subtract, 'x' to exit: ")
if select == "a":
    # code
elif select == "s": 
    # code
elif select == "x": 
    return
do = input("Enter 'n' to print 1 and any other key to print 2)
if do == "n":
    print(1)
    return
else:
    print("2")
    return

# My code:

select = input("Enter 'a' to add, 's' to subtract, 'x' to exit: ")
if select == "a":
    # code
if select == "s": 
    # code
if select == "x": 
    return
print("some text")
do = input("Enter 'n' to print 1 and any other key to print 2)
if do == "n":
    print(1)
    return
print("2")
return

So, does there have to be an elif or else in the last line? Cuz I don't see the point of wasting one line of code when I can just directly type under the if statement.

Aucun commentaire:

Enregistrer un commentaire