CMU 15-110: Principles of Computing
Conditionals


  1. if statement
  2. if-else statement
  3. if-elif-else statement

  1. if statement
    def f(x): result = 'A' if (x == 0): result += 'B' result += 'C' return result print(f(0)) print(f(1))

    A more interesting example:
    # These examples match abs(n), which is a nice example here, but it is # also a builtin function, so you do not need to define it to use it. def abs1(n): if (n < 0): n = -n return n # again, with multiple return statements def abs2(n): if (n < 0): return -n return n # now show that they all work properly: print(abs1(5), abs1(-5)) # 5 5 print(abs2(5), abs2(-5)) # 5 5 (matches!)

  2. if-else statement
    def f(x): result = 'A' if (x == 0): result += 'B' else: result += 'C' if (x == 1): result += 'D' else: result += 'E' result += 'F' return result print(f(0)) print(f(1)) print(f(2))

    Revisiting abs(n):
    def abs3(n): if (n >= 0): return n else: return -n print(abs3(5), abs3(-5)) # 5 5 (still!)

  3. if-elif-else statement
    def f(x): result = 'A' if (x == 0): result += 'B' elif (x == 1): result += 'C' else: result += 'D' if (x == 2): result += 'E' else: result += 'F' result += 'G' return result print(f(0)) print(f(1)) print(f(2)) print(f(3))

    A more interesting example:
    def getGrade(score): if (score >= 90): grade = "A" elif (score >= 80): grade = "B" elif (score >= 70): grade = "C" elif (score >= 60): grade = "D" else: grade = "R" return grade print("103 -->", getGrade(103)) print(" 88 -->", getGrade(88)) print(" 70 -->", getGrade(70)) print(" 61 -->", getGrade(61)) print(" 22 -->", getGrade(22))