I love the challenge of coding, in particular a user friendly
language like Python, I am attempting an excellent Coursera coding course
hosted by Toronto University and thought I would post some simple examples for my own
benefit as well as others who may be interested.


An attempt at currency conversion.
currency.py

#-----------------------------------------------------------------------

Some simple-as-I-can-make-it code snippets.
'''
Converting ints, strings, floats lists etc
'''


#--int to string----------------
num = 4
str(num)
'4'

#--string to int----------------
num_string = '4'
int(num_string)
4

#--int to float -----------------
num = 7
float(num)
7.0

#--string to list -----------------
string1 = '123abc'
list(string1)
['1', '2', '3', 'a', 'b', 'c']

#-- list to dictionary ------------
a = ['1', '2', '3', 'a', 'b', 'c']

b = {}
for i in range(0, len(a), 2):
        b[a[i]] = a[i+1]

print(b)
{'1': '2', '3': 'a', 'b': 'c'}



#----------------------------------------------------------

'''if, elif, else snippet'''
import random

# we generate a number between 1 and 6  ----
random_number = random.randrange(7)

#Now take a guess, is it 6 or 4?

if random_number == 6:
    print("First guess correct!")
elif random_number == 4:
    print("second and last guess correct!")
else:
    print("Failed!")



#--------------------------------------------------------

'''
For loop snippet
Let's add up every tenth number up to one hundred,
'''
total = 0

#--range(start, end, step)------
for number in range(10, 101, 10):
    # Now we loop---
    total = total + number


# finished when loop steps to 101----
print(total)
460


#--------------------------------------------------------

'''
Generator, best way I can describe it is that it acts
as a pause / resume in a loop. Very useful.
'''

def genny():
    '''
    >>> y = genny()
    >>> next(y)
    >>> 1
    >>> next(y)
    >>> 2
    '''
    num = 0
    while num < 10:
        num += 1
        yield num

#--------------------------------------------------------

'''
List of lists to string
'''

string = ''
listofLists = [['1','2'],['3', '4'],['5','6']]

for item in listofLists:
    for items in item:
        string += items

print(string)
'123456'

#---------------------------------------------------------

'''
List.insert
'''

lst = [1, 2, 4]
lst.insert[2, 3]  #insert 3 at index 2
print(lst)
[1, 2, 3, 4]

#---------------------------------------------------------


'''
List Flatten, simple solution
'''

>>>lst = [[1,2,3],['one', 'two', 'three']]
>>>lst = sum(lst, [])
>>>print (lst)
[1, 2, 3 , 'one', 'two', 'three']


#---------------------------------------------------------

'''
string slicing
'''

a[start: end]  # items start through end.
a[start:    ]  # start through the rest of the array.
a[     : end]  # from beginning through end.
a[     :    ]  # copy of the whole array.
a[        -1]  # last item.
a[ -2  :    ]  # last two items.
a[     : -2 ]  # all except the last two items.
a[    :: -1 ]  # reverse the string.
a[ x   :  y ]  # x, index of the first element wanted,
               # y, index of the element you don't want.

#~-----------------------------------------------------------

'''
Simple class example
'''

class BankAccount(object):


    # 'instantiate' the class
    def __init__(self, initial_balance=0):
        # instance variable
        self.balance = initial_balance

    # methods of the class
    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        self.balance -= amount

    def overdrawn(self):
        return self.balance < 0

if __name__ == '__main__':

    my_account = BankAccount(15)
    my_account.withdraw(50)


    print (my_account.overdrawn())

    #------------------------------------------

    Regex

    sentence = re.findall('.+?[.?!]', text
    # Pull sentences from a paragraph


    Check that members of a string are all the same.
    s == len(s) * s[0]

Comments | Gallery