Lesson
This lesson will go over some basic Python statements that haven't been learned in depth yet.
The Assert Statement
The assert statement is primarily used for debugging. If will check a condition and if that condition fails, it will throw an error. The purpose of the assert statement is to test certain conditions before the program actually runs. This can be used to make sure some variable spam is never zero number.
>>> try:
... spam = 0
... assert spam == 0
... spam = 0 / spam
... except:
... print("spam must have been zero!")
... else:
... print("spam wasn't zero!")
...
spam must have been zero!
The In Statement
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 it to check if something 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
Although we can use on the in statement on iterators, we can use it on strings since they're sequences, too. When using the in statement on strings, it will check if a string is within that 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
The is statement is used to check if two are variables unique. This means that both variables aren't the same 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 string. Since these aren't the same string, they 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, all though they have the same text in their strings, each string is created uniquely and put into memory positions. 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
The pass 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 leave a code block empty.
>>> if True:
... pass
...
>>> for spam in range(10):
... pass
...
|