The Anatomy Of A Python Class

class Customer:

    #global limit = -1000

    def __init__(self):
        #in a real app these values would be provided most likely by a database
        self.balance = 0
        self.limit = -1000
        self.security_check = True
        self.is_active = True

    def credit_limit(self, balance):
        #limit = -1000
        if balance < self.limit:
            return False
        else:
            return True

    def withdraw(self, amount):
        #act_balance = self.balance - amount
        self.balance -= amount
        if (self.credit_limit(self.balance) == True):
            return self.balance
        else:
            return ("Withdrawl not possible. You reached the credit limit.")

    def deposit(self, amount):
        self.balance += amount
        return self.balance



a = Customer()

b = Customer()

print(a.withdraw(500))                        #   - 500
print(a.deposit(100))                         #   - 400

print(b.withdraw(1500))                       #   Withdrawl not possible. You reached the credit limit.

Day 69: Make Good Looking Tables With PrettyTable (Module)

 

Scripts running in the shell are pretty cool. But sometime you want to display tables that have no real format.

 

The module PrettyTable generates some – well pretty – tables with just a couple of lines.

 

The script takes a dictionary with the sizes of all planets in the solar system.

 

It exports it in a PrettyTable in descending order.

 

# PrettyTable module
# Create handsome tables in your shell
from prettytable import PrettyTable

planets = {"Mercury" : "4879",
        "Venus" : "12104",
        "Earth" : "12756",
        "Mars" : "6779",
        "Jupiter" : " 142984",
        "Saturn" : "120536",
        "Uranus" : "50724",
        "Neptune" : "49244"
        }

# create the table with two colums
size_table = PrettyTable(["Planet", "Diameter (km)"])

# go over every planet in dict and add a row for each
for item in planets:
    size_table.add_row([item, planets[str(item)]])

# sort planets from big to small
size_table.sort = True

print(size_table)

The output looks like this:

 

 

Day 66: Being A Scribe – Read From And Write To Files

# Read and write files

# open the file with 'write'-mode
test_file = open("files_test.txt", "r")


# full list of file modes
# "w" - write text file (overwrite possible)
# "r" - read text file
# 'x' - write text file (includes error is file exists)
# 'a' - append to end of file
# 'rb' - read binary files
# 'wb' - write binary
# 'w+b' - read and write binary file
# 'xb' - write binary file (includes error is file exists)
# 'ab' - append to end of binary file

# Read files
print(test_file.read())                     # This is a test - full text

# Read one line
print(test_file.readline())                  # This is a test - one line


# iterate over text files
for line in test_file:
    print(line)                              # This is a test - all lines

# readline() is not very well suited to iterate over big files

# close files - you should alway close a file after using it!!!
test_file.close()

# Write to files
texty = open("files_test.txt", 'w')
texty.write("11 This is a test\n")
print(texty.read())
texty.close()

Day 64: Check If A String is a Palindrome With Python

 

We get a string and check if it is a palindrome:

 

# Find out if a word is a palindrome
def palin(word):
    ''' take word, build inverted string
    and check if it is a palindrome '''

    word = word.replace(".", "")    # get rid of eventual "."
    word = word.lower()             # make lowercase

    length = len(word)
    new = list("")                  # build an empty list for the inversed string
    index = -1                      # -1 so we start building in reverse order

    # take every letter and add it to new list in reverse order
    for i in word:
        new.insert(index, i)
        index -= 1

    # change list to string
    new_str = "".join(new)

    # get rid of any spaces in a sentence
    word_stripped = word.replace(" ", "")
    new_stripped = new_str.replace(" ", "")

    # check if word and the reverse string are the same
    if (word_stripped == new_stripped):
        return (word + ": This is a palindrome")
    else:
        return (word + ": This is NOT a palindrome")

print(palin("Anna"))                    # anna: This is a palindrome

print(palin("peter"))                   # peter: This is NOT a palindrome

print(palin("Name not one man."))       # name not one man: This is a palindrome

Day 63: Indexing And Slicing

# Indexing
# note: sets can't be indexed

my_guitars = ["Gibson Les Paul", "Ibanez RG", "Fender Stratocaster"]

print(my_guitars[0])                # Gibson Les Paul

# Python allows negative indexing. -1 returns the last item aso
print(my_guitars[-1])               # Fender Stratocaster
print(my_guitars[-2])               # Ibanez RG


# indexing a tuple
print(("Marshall", "Laney", "Orange")[1])       # Laney

# indexing a string
print("Wampler"[3])                 # p - index starts at 0

# slicing
print(my_guitars[0:2])              # ['Gibson Les Paul', 'Ibanez RG']


# note: the first index is optional. negative indexing works here as well
print(my_guitars[:2])              # ['Gibson Les Paul', 'Ibanez RG']
print(my_guitars[:-1])              # ['Gibson Les Paul', 'Ibanez RG']


#Examples

# get first and last letter
name = "Robert"

print(name[0])                      # R
print(name[-1])                     # t

# delete the file extension
filename = "document.txt"

print(filename[0:-4])               # document

Day 61: Functions Overview

# Functions

# declaring a Function
# if there is no return in the Functions
# python will return the last command line

def func(para1, para2):
    ''' explain what happens here '''
    sum  = para1 + para2                # variables declared inside functions are local
    return sum

#calling a function
sum = func(13,5)               # 18 this sum is not related to the sum-variable in the function
print(sum)


#using default parameters
def def_func(x, y=3):          # y=3 is a default parameter
    return x + y

print(def_func(2))             # 5 - the function will use the default parameter

print(def_func(5,8))           # 13 - default parameters can be overwritten


# Examples:

def is_odd(num):
    ''' returns true if number is odd '''
    if (num % 2 == 0):
        return True
    else:
        return False

print(is_odd(4))                                    # True


def is_prime(x):
    ''' checks if number is prime '''
    ''' only natural number bigger 1 can be considered primes '''
    if (x > 1):
        return all(x % i for i in range(2, x))
    else:
        return False                                # if number is 1 or less

print(is_prime(3))                                  # True