Calling Functions from Functions


In [115]:
def add_together(one, two):
    one = one + two
    return one

def mutiply_and_add(one, two):
    one = add_together(one, two)
    return one * one

temparary_value = mutiply_and_add(2, 3)

print(temparary_value)
print(mutiply_and_add(2, 3))


25
25

Interating over a collection

Make the 12 x 12 times table


In [119]:
number_1 = 10
number_2 = 30
print(len(str(number_1 * number_2)))
print(len(number_1 * number_2))


3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-119-b246ade6188d> in <module>()
      2 number_2 = 30
      3 print(len(str(number_1 * number_2)))
----> 4 print(len(number_1 * number_2))

TypeError: object of type 'int' has no len()

In [140]:
some_string = 'cow'

print(some_string)

some_string = some_string + ' town'

print(some_string)

print('\n\n\n\n')

print('meow cats'.ljust(10))

words = ['one', 'two']
words_two = words

words[0] = 'dinasour'

print(words)
print(words_two)

print(ord('z'))
print(ord('a'))
print(ord('z') - ord('a'))


cow
cow town





meow cats 
['dinasour', 'two']
['dinasour', 'two']
122
97
25

In [143]:
import math

# Cannot range over infinity
for i in range(math.inf):
    print(i)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-143-6195d980e1cc> in <module>()
      1 import math
      2 
----> 3 for i in range(math.inf):
      4     print(i)

TypeError: 'float' object cannot be interpreted as an integer

In [130]:
def get_rows():
    return [1,2,3,4,5,6,7,8,9,10,11,12]

def get_columns():
    return [1,2,3,4,5,6,7,8,9,10,11,12]

def get_max_width(first_number, second_number):
    """
    Return the widest a given mutiplication times table cell should be
    """
    highest_value_str = str(first_number * second_number)
    
    return len(highest_value_str) + 2 # Add two to make it appear to be one bigger on each side


rows = get_rows()
columns = get_columns()
max_width = get_max_width(max(rows), max(columns))
output = ''

# Go over the numbers to produce each row in the times table
for row_value in rows:
    
    # Create each column in the times table with this for loop
    for col_value in columns:
        product_str = str(row_value * col_value)
        output = output + product_str.rjust(max_width)
    
    # Add a new line after each set of numbers to ensure the next
    # number in the times table gets its own row.
    output += '\n'

print(output)


    1    2    3    4    5    6    7    8    9   10   11   12
    2    4    6    8   10   12   14   16   18   20   22   24
    3    6    9   12   15   18   21   24   27   30   33   36
    4    8   12   16   20   24   28   32   36   40   44   48
    5   10   15   20   25   30   35   40   45   50   55   60
    6   12   18   24   30   36   42   48   54   60   66   72
    7   14   21   28   35   42   49   56   63   70   77   84
    8   16   24   32   40   48   56   64   72   80   88   96
    9   18   27   36   45   54   63   72   81   90   99  108
   10   20   30   40   50   60   70   80   90  100  110  120
   11   22   33   44   55   66   77   88   99  110  121  132
   12   24   36   48   60   72   84   96  108  120  132  144

Iterating over a list of strings

Shows how to iterate over strings and that you can iterate over sub collections as well


In [142]:
# For each word in our list of words I want to "translate" it
from random import shuffle

new_alphabet = ['l', 'i', 'g', 'a', 'f', 'x', 'o', 'e', 'v',
                'y', 'r', 'b', 'd', 'h', 'm', 'p', 'k', 'u',
                'w', 'j', 's', 'q', 'c', 'z', 't', 'n']

words = ['The', 'quick', 'brown', 'fox',
         'jumps', 'over', 'the', 'lazy', 'dog']

# Normalize the words
position = 0
for word in words:
    words[position] = word.lower()
    position += 1

# Go over each word and replace it with the 'modified' word
# Create a new list so that we do not modify the original
word_index = 0
new_words = list(words)
for word in words:
    # Initialize the new word
    new_words[word_index] = ''
    
    # Go over and setup each new word replacing the old letters
    for letter in word:
        new_alphabet_position = ord(letter) - ord('a')
        new_words[word_index] += new_alphabet[new_alphabet_position]
    
    # Increase the word index so we populate the word in the list correctly
    word_index += 1
        

print('Existing words: ', words)
print('New words: ', new_words)


Existing words:  ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
New words:  ['jef', 'ksvgr', 'iumch', 'xmz', 'ysdpw', 'mqfu', 'jef', 'blnt', 'amo']

Default Parameters


In [159]:
import math

def times_x(value, x=10):
    return value * x

def divide_x(value, x=None):
    if x == None:
        return 0
    
    elif x == 0:
        return math.inf # This is infinity
    
    return value / x


print('one', times_x(10))
print('two', times_x(10,5))
print('two', divide_x(20, 10))
print('two', divide_x(20, 0))
print('one', divide_x(20))

def broken_times(x, y):
    if y == None:
        y = 10
    return x * y

# print(broken_times(10))

def x_times_y(x, y):
    if type(x) == int and type(y) == int:
        return x * y
    return None


product = x_times_y(2, 4)
print(product)

product = x_times_y(None, 2)
if type(product) == type(None):
    print('I have no product')
else:
    print(product)


one 100
two 50
two 2.0
two inf
one 0
8
I have no product

Bonus: Testing your code

Here is an easy way to test that your code does what you want


In [160]:
def test_values(first_value, second_value):
    """
    Asserts that the first and second parameters have the same value
    
    Raises an AssertionError if they are different with a message
    """
    failed_message = "{0} is not equal to {1}".format(first_value, second_value)
    assert first_value == second_value, failed_message

    
def is_prime(x):
    if x in [1,2,3,5,7,11,13,15,17]:
        return True
    return False


primes = [1,2,3,5,7,11,13,15,17,19,23]
for prime in primes:
    print(prime)
    test_values(is_prime(prime), True)


1
2
3
5
7
11
13
15
17
19
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-160-71b0c9943989> in <module>()
     18 for prime in primes:
     19     print(prime)
---> 20     test_values(is_prime(prime), True)

<ipython-input-160-71b0c9943989> in test_values(first_value, second_value)
      6     """
      7     failed_message = "{0} is not equal to {1}".format(first_value, second_value)
----> 8     assert first_value == second_value, failed_message
      9 
     10 

AssertionError: False is not equal to True

Studio: Bugz


In [ ]: