Python Concepts/Other Statements
Objective
[edit | edit source]
|
Lesson
[edit | edit source]
This lesson will go over some basic Python statements that haven't been learned in depth yet. The Assert Statement[edit | edit source]The This code illustrates use of the 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 | edit source]You might remember the >>> "and" in ("or", "xor", "and", "not")
True
>>> "inv" in ("or", "xor", "and", "not")
False
>>> "a" in ("aa", "aaa", "aaaa")
False
Which members of >>> [p for p in ("or", "xor", "and", "not") if 'n' in p]
['and', 'not']
>>>
Although we can use the >>> "a" in "aaa"
True
>>> "spam" in "spa"
False
>>> "spa" in "spam"
True
>>> "cake" in "pancake"
True
The Is Statement[edit | edit source]The >>> spam = "Hello!"
>>> eggs = "Hi!"
>>> spam is eggs
False
>>> spam = "Hello!"
>>> eggs = "Hello!"
>>> spam is eggs
False
>>> spam = "Hello!"
>>> eggs = spam
>>> spam is eggs
True
The pass Statement[edit | edit source]The >>> if True:
... pass
...
>>> for spam in range(10):
... pass
...
The del Statement[edit | edit source]The >>> 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 >>> 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 | edit source]
|
Further Reading or Review
[edit | edit source]
|
References
[edit | edit source]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: