Beginner introduction to Python – Part 3

Continuing my learning path into python I will create some example scripts that shows some of the cool things that could be done with python. The scripts could be accessed via the git repository here. You could download them and try them out. After this I will finally consider myself ready to create a web application using Django web framework. (Lol..I was always ready).

Multiply.py

The first example file is a simple console app that asks you for two numbers and multiplies them and returns the results. All of the apps we create are console apps though. This app has two main sections

def multipy_function():
    x = input("Enter your first number:\n")
    y = input("Enter your second number:\n")
    sum = int(x) * int(y)
    print("Output = " + str(sum))

The multipy_function asks for two inputs from the user. These inputs x and y are converted to an int variable and multiplied. The result it printed for the users to see.

The second section consists of a while loop the runs the logic until the users says no or an error occurs.

while loop:
    multipy_function()
    next = input("Multiple next function? y /n\n")
    if next == "n":
        loop = False
    elif next == "y":
        loop = True
    else:
        loop = False

The while loop checks the input for a “y” or a “n” if it sees neither the loop is terminated by setting loop as False. At the start of the while loop the multipy_function is executed.

Some things to note

  • The input function gets input from the user via console
  • You can convert the input to a format that you need it to be in

Bank_account.py

The bank_account.py file simulates – kind off – some bank account features. Find this file here. You can do the following:-

  • Show all your accounts
  • Select an account to work on
  • Deposit money to a selected account
  • Retrieve the account balance from the selected account
  • Add an account
  • Close the program.

The program loops through a main function called run_program that asks you these questions and then performs the operations to carry them out. Once you are finish it returns to the above options. In creating this example I created an Account class to simulate a bank account. The main program interacts with the class do carry out the functions. It stores all the created accounts in a global list. Another global variable called current_account stores the list index of an account. This index will be used to retrieve the class from the list.

Account Class Methods

  • get_balance – Allows you to get the balance from your account
  • get_owner – Get the owner of the account
  • get_type – Get the type of the account ( e.g savings )
  • deposit – Add money to the account
  • add_to_balance – Add a given amount to the account balance

bank_account.py functions

  • show_all_accounts – displays the list of accounts if there are any
  • get_total_accounts – uses the len function to get the count of accounts from the list that holds the classes
  • select_account – sets the global current_account variable to the suggestion account if you have any accounts
  • is_account_selected – checks to see if any accounts are selected
  • add_account – adds an account to the accounts list
  • deposit_account – adds money to the current selected account
  • get_account – returns the current selected account object
  • account_balance – shows the current balance for the currently selected account
  • add_default_account – adds a default account for you to play with when the app starts.
  • run_program – the main function.

Turns out python doesn’t do switches so for the run_program function we have a list of if else statements. No issue works the same. I can’t go through this entire file but I listed some things to note.

Some things to note

  • The class objects are stored in the accounts list.
  • the function len was used on the accounts list to get the amount of objects in it.
  • Python doesn’t do switch statements
  • To access a global variable in a function you need to declare it as global in the function and then use it. You can see an example of this in the select_account function.
  • We added new accounts using the append function to the global accounts list.

Simple_chat.py

Simple_chat.py creates a simple chat. Find this file here.It asks the user to ask a question and responds via a hard coded list of responses. The responses are stored via a dictionary. The keys have the keywords for the responses and the values are the responses the chat returns. The dictionary is seen below.

responses = {
    "hello,hi,sup": "Hey you. Whats up?",
    "bye, goodbye, later, ltr": "Alrite, Later.",
    "name, title": "Simple Chat Bot",
    "age": "Im new",
    "exit,close": "Closing program"
}

More items can be added to the dictionary to make it more versatile.

Functions

check_matches

This function takes in the dictionary key and the user input. It splits both by the delimiter “,” and checks them against each other. The number of matches for the key gets returned.

get_response

This function takes the uses response and send its to the check_matches function. It keeps track of the highest matches returned from check_matches. The key with the highest matches gets returned to the main function.

talk

This is the main function. It takes the the user input and sends it to the get_response function. The correct response is sent to the console using the key returned from the get_response function. If the get_response function doesn’t return a valid value it outputs “I don’t understand” to the console.

Things to note

  • We use the strip() function to remove white space
  • To compare two strings exactly we use the set function.
  • In the talk function we check for a null value using the if not statement
  • We use the lower function on a string to ensure all matches are in lowercase.
  • We use the split function and pass in a delimiter to created lists from a comma separated string.

Note_book.py

This file allows the user to create text file and add content to the file line by line. It makes use of file functions open and write in python.

There are two functions of note in this file. The write_file function takes content and appends it to an already created file. If the file hasn’t been created it will be.

def write_file(content):
    f = open("note.txt", "a+")
    f.write(content)
    f.close()

The open_file function is used to read the contents of the file being edited.

def open_file():
    f = open("note.txt", "r")
    if f.mode == "r":
        print(f.read())

The function that manages the previous two functions is called get_input. It gets the input from the user and writes it to a file.

def get_input():
    content = input("Write Line:?")
    write_file(content.strip() + "\r\n")
    open_file()

The functions in this one is pretty straight forward. To learn more you can check out the tutorial I used to understand this here. This site has some really good info in general there.

Websites_title.py

This file takes a url and displays the title of that website. To do this we added two imports

import urllib.request
from pyquery import PyQuery

and that was the hardest part. Urllib takes care of get the content from the webpage and pyquery gets the title element. This is shown in the get_url_title function.

def get_url_title(url):
    html = urllib.request.urlopen(url)
    content = html.read()
    pq = PyQuery(content)
    tag = pq("title")
    print(tag.text())

The main function deals with looping and getting the url from the user input.

Conclusion

So python is finished. There is a lot more to do in python and I will be back with it to do those things but for now I’ll stay focus on web development using the Django framework. I recently learnt about web2py which is pretty cool and on the books to look at as well.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s