Glossary

Select one of the keywords on the left…

Programming in PythonConditionals

Reading time: ~10 min

Consider a simple computational task performed by commonplace software, like highlighting the rows in a spreadsheet which have a value larger than 10 in the third column. We need a new programming language feature to do this, because we need to conditionally execute code (namely, the code which highlights a row) based on the value returned by the comparison operator. Python provides if statements for this purpose.

Conditionals

We can use an if statement to specify different blocks to be executed depending on the value of a boolean expression. For example, the following function calculates the sign of the input value x.

def sgn(x):
    if x > 0:
        return +1
    elif x == 0:
        return 0
    else:
        return -1

sgn(-5)

Conditional expressions can be written using ternary conditional «truevalue» if «condition» else «falsevalue». For example, the following version of the sgn function returns the same values as the one above except when x == 0.

def sgn(x):
    return +1 if x > 0 else -1

sgn(-5)

Exercises

Exercise
Can the else part of an if statement be omitted? Try running the example below.

x = 0.5
if x < 0:
    print("x is negative")
elif x < 1:
    print("x is between 0 and 1")

Exercise
Write a function called my_abs which computes the absolute value of its input. Replace the keyword pass below with an appropriate block of code.

def my_abs(x):
    pass # add code here

def test_abs():
    assert my_abs(-3) == 3
    assert my_abs(5.0) == 5.0
    assert my_abs(0.0) == 0.0
    return "Tests passed!"

test_abs()

Exercise
Write a function which returns the quadrant number (1, 2, 3, or 4) in which the point (x,y) is located. Recall that the quadrants are numbered counter-clockwise: the northeast quadrant is quadrant 1, the northwest quadrant is 2, and so on. For convenience, you may assume that both x and y are nonzero.

Consider nesting if...else blocks inside of an if...else block.

def quadrant(x,y):
    pass # add code here

def test_quadrant():
    assert quadrant(1.0, 2.0) == 1
    assert quadrant(-13.0, -2) == 3
    assert quadrant(4, -3) == 4
    assert quadrant(-2, 6) == 2
    return "Tests passed!"

test_quadrant()

Solution. Here's an example solution:

def quadrant(x,y):
    if x > 0:
        if y > 0:
            return 1
        else:
            return 4
    else:
        if y > 0:
            return 2
        else:
            return 3

To reveal more content, you have to complete all the activities and exercises above. 
Are you stuck? or reveal all steps

Next up:
Functions
Bruno
Bruno Bruno