CMSC 201

Lab 3: Simple Logic Programming

If-else Statements

What are they?

Decision statements such as "if-else" are also called conditionals. They are useful for decision making within a program. For example, if you have to decide if a number is positive or negative you would need an if statement. If it is positive, do one thing, else do another.

How do I use them?

In most programming languages, you can do a simple if statement, an if-else statement, or a series of if-else statements.

  1. A basic if statement would look like this:
    if(num >= 0):
      print("non-negative")

  2. You can also add an else statement to this if you want to do something whether it is or it isn't true:
    if(num >= 0):
      print("non-negative")
  3. else:
      print("negative")

  4. If you have several options, such as wanting to differentiate between 0 and positive numbers in our example:
    if(num > 0):
      print ("positive")
  5. elif(num == 0):
      print("zero")
    else:
      print("negative")

  6. You can combine two if statements into one using "and" or "or", this is useful if you want to do the same thing for multiple conditions:
    if(num > 0 and num % 2 == 0):
      print("positive even number")

If you put two if statements back-to-back without an else or elif it will check both. If you use an elif or else it will only run if the above if statement is false.