In [1]:
tup = ('a', 'b', 'c')
a, b, c = tup
print(a)
print(b)
print(c)
In [2]:
print('Unpacking a list...')
a_list = ['a', 'b', 'c']
a, b, c = a_list
print(a)
print(b)
print(c)
In [3]:
print('Unpacking a string...')
a_string = 'abc'
a, b, c = a_string
print(a)
print(b)
print(c)
In [4]:
def parse_request(request):
try:
method, uri, protocol = request.split(' ') # expect list of length 3
return('200 OK')
except ValueError:
return('400 Bad Request')
print(parse_request('GET /login.html HTTP/1.1'))
print(parse_request('GET /login.htmlHTTP/1.1'))
In [5]:
dictionary = {'a': 0, 'b': 1, 'c': 2, 'd': 3}
In [6]:
for key in dictionary:
value = dictionary[key]
print('{}: {}'.format(key, value))
In [7]:
for key, value in dictionary.items():
print('{}: {}'.format(key, value))
In [8]:
a_list = [5, 2, ('x', 'y'), 7.7, 9, 'c', 10, 2, 'a']
In [9]:
for index in range(len(a_list)):
item = a_list[index]
print('Item at index {} is {}'.format(index, item))
In [10]:
for index, item in enumerate(a_list):
print('Item at index {} is {}'.format(index, item))
In [11]:
print(True or False)
In [12]:
print(False or True)
In [13]:
print(False or 0 or '' or [] or {} or 'Finally, something Truthy!')
In [14]:
def get_a_string():
"""
Return a useful string if you're lucky.
Return empty string for no result.
"""
return ''
In [15]:
result = get_a_string()
if not result:
result = 'No results found.'
In [16]:
result = get_a_string() or 'No results found'
In [17]:
def get_a_string_usually():
"""Return a string if you're lucky, return None for no result."""
return None
value = get_a_string_usually() or ''
In [18]:
a = 'a'
b = 'b'
In [19]:
c = a
a = b
b = c
print('a = {}'.format(a))
print('b = {}'.format(b))
In [21]:
a, b = b, a
print('a = {}'.format(a))
print('b = {}'.format(b))
In [22]:
a_list = [1, 2, 3, 4]
a_list[0], a_list[1] = a_list[1], a_list[0]
print(a_list)
In [ ]:
def reverse_linked_list(linked_list):
"""Reverse a Linked List and return it."""
node1 = linked_list.head
node2 = linked_list.head.next
while node2.next:
node2.next, node2, node1 = node1, node2.next, node2
return node2
In [23]:
try:
print('a string' + 2)
except TypeError:
print('Not OK!')
In [24]:
print(' a string' * 2)
In [25]:
print(1 + False)
print(1 + True)
In [26]:
print(10 * True)
print(10 * False)
In [27]:
print(True == 1)
print(False == 0)
In [28]:
list_of_nums = [7, 2, 0, 3, 99, 11]
insert_num = 10
insertion_index = sum(num < insert_num for num in list_of_nums)
print(insertion_index)
In [29]:
for n in range(16):
divides_by_3 = n % 3 == 0 # Boolean statement
divides_by_5 = n % 5 == 0 # Boolean statement
fizz = 'Fizz' * divides_by_3 # str * bool
buzz = 'Buzz' * divides_by_5 # str * bool
fizzbuzz = fizz + buzz
print(fizzbuzz or n)
In [30]:
for n in range(16):
print('Fizz' * (n % 3 == 0) + 'Buzz' * (n % 5 == 0) or n)