Back

Another way of testing using 'if'

Introduction
There is a neat way of testing if a string, list or tuple has something in it or is empty, or whether a number is zero. Copy the following code into Python:

#strings, lists and tuples

def test_string(try_this):
    if try_this:
        return '\nThe string has something in it so do this block.\n'
    else:
        return '\nThe string is empty so do this block.\n'

string1 = ''
string2 = 'Hello'
print('string1: ',test_string(string1))
print('string2: ',test_string(string2))


def is_empty(try_this):
    if try_this:
        return "\nThe list has at least one element in it so 'if try_this' is True.\n"
    else:
        return "\nThe list is empty so 'if try_this' is False.\n"

list1 = []
list2 = ['Jack', 'Mary', 'Dave']
print('list1: ',is_empty(list1))
print('list1: ',is_empty(list2))

Look at the rather curious line in the two functions if try_this: This is still a Boolean test, even if it doesn't look like one! The variable try_this is examined. If it has something in it, anything at all, then True is returned. If it is empty, then False is returned.

Tasks:
Q1. Test to see if this will work for a tuple.
Q2. Modify the second function so that it simply returns the Boolean value True if there is something in the list and the Boolean value False if it is empty.
Q3. Enter this code into Python:

def is_not_zero(try_this):
    if try_this:
        return "\nThe number is not zero so this is True.\n"
    else:
        return "\nThe number is zero so this is False.\n"

num1 = 5
num2 = 0
print('num1: ',is_not_zero(num1))
print('num2: ',is_not_zero(num2))

What do you think will happen? Try it and see if you were correct. Predict what will happen with different values e.g. -6, -50.34, 0.0, 105.65, 'R', 'True', 'False'.

Back