Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Why don't you put a variable before an else statment?

  1. Sep 27, 2015 #1
    I'm too lazy to see the big picture. Here is an example to show you what I'm talking about:

    x = str(input())
    if x == "that's a nice meme sir":
    print("thanks friend")
    elif x == "crap meme stop posting anytime":


    Why don't you put the variable in front of else? Don't you have to clarify what variable you want else to apply to? Thanks.
  2. jcsd
  3. Sep 27, 2015 #2
    You can think of the else in a couple of ways. One, as being there in error... If you expect a variable to be either one or two with different actions for each value you can do an if and an elif for one and two then if you end up in the else, it is because the value is not one or two... So you may want to place an error message in the else and even possibly quit the program

    The other possibility, it is simply the you don't care what the value is our you have done enough validation before hand that you know what the value will be... For example, if you have an if x<1 followed by an else, then clearly x will be >= 1 in the else.
  4. Sep 28, 2015 #3


    Staff: Mentor

    The else keyword doesn't apply to variables. It applies to a section of code in your Python code.

    The output from the sample below is
    Code (Python):
    import sys
    x = 2
    if x == 1:
      print('x is 1')
      print('x is not 1')
    If the expression x == 1 is true, the first print statement executes, and then the code displays Done.
    If the expression x == 1 is false, the second print statement executes, after which the code again displays Done.

    The value of the variable x is immaterial; what's important is whether the boolean expression happens to be true (in which case the statement or statements associated with the if portion execute) or false (causing the statements associated with the else clause to execute).
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook