Python Concepts/Other Statements

Objective

edit
 
  • Learn about the assert statement.
  • Learn about the in statement.
  • Learn about the is statement.
  • Learn about the pass statement.

Lesson

edit

This lesson will go over some basic Python statements that haven't been learned in depth yet.

The Assert Statement

edit

The assert statement is primarily used for debugging. It depends upon the value __debug__ being True (which it is under normal circumstances.) It will check a condition and if that condition fails, it will raise an AssertionError. The purpose of the assert statement is to test certain conditions before the program actually runs.

This code illustrates use of the assert statement:

print ('__debug__ =', __debug__ )

for spam in (0,1) :
    print ('\nspam =', spam)

    try:
        assert spam == 0 # Checking that spam is zero.
    except AssertionError:
        print("AssertionError detected!")
    except:
        print("Unknown error detected!")
    else:
        print("spam was zero, no error raised!")

    try:
        if not spam == 0 : raise AssertionError # Equivalent to "assert" above.
    except AssertionError:
        print("AssertionError detected!")
    except:
        print("Unknown error detected!")
    else:
        print("spam was zero, no error raised!")
__debug__ = True

spam = 0
spam was zero, no error raised!
spam was zero, no error raised!

spam = 1
AssertionError detected!
AssertionError detected!

The In Statement

edit

You might remember the in statement when working with the for statement in an older lesson. Although the in statement was used in conjunction with a for statement, the in statement can be used by itself. The primary purpose of the in statement is to check if something is in a sequence. This means the in statement returns a Boolean value: True or False.

>>> "and" in ("or", "xor", "and", "not")
True
>>> "inv" in ("or", "xor", "and", "not")
False
>>> "a" in ("aa", "aaa", "aaaa")
False

Which members of ("or", "xor", "and", "not") contain the letter 'n'?

>>> [p for p in ("or", "xor", "and", "not") if 'n' in p]
['and', 'not']
>>>

Although we can use the in statement on iterators, we can use it on strings because they're sequences, also. When using the in statement on strings, the statement will check if a string is within a second string. This means you can check for part of a word within a word.

>>> "a" in "aaa"
True
>>> "spam" in "spa"
False
>>> "spa" in "spam"
True
>>> "cake" in "pancake"
True


You should remember that using the in statement is one of the fastest ways to compare two variables.

The Is Statement

edit

The is statement is used to check if two variables are unique. This means that both variables don't have the same value, or they don't point to the same value. This means, unlike == which is used for equality comparison, is is used for identity comparison.

>>> spam = "Hello!"
>>> eggs = "Hi!"
>>> spam is eggs
False


In the above example, two variables are created, spam and eggs. They are both assigned to two different strings. Because these aren't the same string, the variables aren't the same. Now let's create both of the variables with the same text in their strings.

>>> spam = "Hello!"
>>> eggs = "Hello!"
>>> spam is eggs
False


spam and eggs still aren't the same. This is because, although they have the same text in their strings, each string is created uniquely and put into its own memory position. To have the two variables point to the same string, you'll need to assign one of the variables to the other.

>>> spam = "Hello!"
>>> eggs = spam
>>> spam is eggs
True

The pass Statement

edit

The pass statement is used mostly for syntactic sugar and serves as a nop. This means that the pass statement doesn't do anything. The primary purpose of the pass statement is to provide a statement when the syntax requires it, but when no action is required.

>>> if True:
...     pass
...
>>> for spam in range(10):
...     pass
...

The del Statement

edit

The del statement is used to remove or delete members of a mutable sequence.

>>> L1 = [1,2,3,4]
>>> del L1[2]
>>> L1
[1, 2, 4]
>>> 
>>> L2 = [0,1,2,3,4,5,6,7]
>>> del L2[5:10] ; L2
[0, 1, 2, 3, 4]
>>> 
>>> dict1 = dict([('one',1),('two',2),('three',3)]) ; dict1
{'one': 1, 'two': 2, 'three': 3}
>>> del dict1['two']
>>> dict1
{'one': 1, 'three': 3}

To delete a global variable delete it from dictionary globals():

>>> v3 = 2.5
>>> globals()['v3']
2.5
>>> del globals()['v3']
>>> v3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'v3' is not defined
>>>

Strings and tuples are not mutable sequences:

>>> t1 = (1,2,3,4)
>>> del t1[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion
>>> s1 = 'abcdef'
>>> del s1[1:3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item deletion
>>>

Assignments

edit
 
  • Work with the assert, in, is, and pass statements.

Further Reading or Review

edit
  Completion status: Ready for testing by learners and teachers. Please begin!

References

edit

1. Python's documentation:

"7.3. The assert statement," "7.4. The pass statement," "7.8. The raise statement," "7.5. The del statement"

2. Python's methods:


3. Python's built-in functions: