Featured

Automating Web Browsers with Python

If you use the same tabs in a Web browser every day, it can seem menial and time consuming opening each tab individually. So, today I’m going to show you how to open all of the tabs you use with one double click.

To start off with, we’re going to need to open a text editor. For this, I’m using Visual Studio, but you can use any text editor. Just remember to save the file with a .py extension. For example: Workflow.py

To begin with, we need to import the ‘webbrowser’ module. This module is responsible for launching and controlling Web Browser Functions. If you are working on Windows, the program will use whatever browser is set as the default. In this case, the tabs will open in Firefox.

After importing the ‘webbrowser’ module, it is time to set up opening Firefox. For this demonstration I am going to load https://www.google.co.uk. The code for that is ‘webbrowser.open_new(“https://www.google.co.uk)

Now that we have written the open browser function, it is time to amend it, so that it will open the following web page in a new tab. This is simply done by amending the previous code to add ‘_tab’ on the end like so: webbrowser.open_new_tab(https://www.facebook.com)

To open any additional tabs from here will also use the ‘_new_tab’ function. This can be used to open as many tabs as needed. Printed below is the full program that I have written for this demonstration.

As displayed in the program, the file is saved as ‘WorkFlow.py’, this is a file that I have saved to the desktop. The image on the desktop shows the Python logo to confirm it has been saved as a Python executable file.

To run the program, just double-click and as you can see in the Screenshot below, it has opened the three webpages that we were setup in the program.

Congratulations, you have just automated the opening of various webpages using Python programming.

Featured

Getting Started with Python in Linux

Getting started with Python in Linux

There is no need to install Python on Linux as it comes preinstalled. After opening the Terminal, the first thing to do is to create a folder that will contain all of the Python files.
To create a folder named Python, type ‘mkdir Python’.

mkdir Command

After creating the Directory, we are now ready to create our first “Hello World” program.
To get to the Directory that was created in the previous step, use the command “cd Python”

Change Directory Command

Once we have created and moved into the Directory, we are now ready to start our first program on Linux.
To create the our first file, we are going to use the ‘Touch’ command, and name our file something that is easy to remember for later on. In this instance we are going to call the file, “Hello.py”. We have the .py extension because it is a Python File.
When we use the ‘Touch’ Command in Linux. It doesn’t look like anything has happened. However, if you type ‘ls’ and press enter. This will list all files in the current directory, and as you can see from the screenshot below, there is currently only one file in the directory.

Demonstrating File Creation and Listing in the Terminal

It is now time to edit the file, and to do this we are going to use the VIM editor. Similar to before we are going to type ‘vim’ followed by the document name. e.g. vim Hello.py
It may be difficult to see in the image below. However, there are some key things to point out. Firstly, in the bottom left corner of the window, you can see the file name that we are currently working on.
Secondly, vim opens in a ‘read-only’ mode. For us to be able to edit it, we need to press ‘I’ on the keyboard, which will allow us to start editing the document. When you start editing the document, the file name will disappear from the bottom left of the screen and be replaced with the word ‘Insert’. This lets us know that we can start making changes.

Vim Editor

You can write anything you want for your first program using Python. Type the following code:
print(“A string of Text”)
Once you are happy with the code that you have written, we need to exit vim and go back to the Terminal window. To exit vim, enter the following command: Esc key :wq!
That command will convey to the editor, that you have finished typing and that you wish to write the changes to file and quit.
It is now time to run our Python Program. To do this type: python3 Hello.py
It will display the string of text in the Terminal window, as shown below.

Output of First Python Program in Linux

Congratulations, you have just learnt some basic navigation through the Linux Terminal and created your first program in Python using Vim.

Terminal Commands in Ubuntu Linux

The Linux Terminal is a very powerful application and can be used to achieve just about anything.
I am going to run through some of the basic commands that you need to know, to get setup using Linux and on your way to becoming a command line master.
An important point to mention before we go any further with terminal commands is the use of ‘sudo’ or ‘root’ privileges. Sudo or root is required to run commands using elevated privileges. 
The Terminal has a manual built into it with entries for all commands. This includes a description of what the command does and how it can be used.
The manual page can be accessed by typing ‘man <name of command>’. So, to see the manual page for ‘sudo’, we would type, ‘man sudo’.

Manual Pages

For security reasons, it is important that your computer is regularly kept up to date with the latest updates. Now, we could do this through the Graphical User Interface (GUI) that can be accessed through ‘Ubuntu Software’, navigating across to the ‘Updates’ tab and installing all available updates. However, that is boring and slow.
Instead, let’s use the command ‘sudo apt-get update && sudo apt-get upgrade’. The ‘&&’ operator combines the two commands together and runs them one after the other. After running the command, the terminal will prompt for a password, and then require either a Y/N to confirm or deny the updates.

Update Command

Updates have now been completed. Now, I need to see which folders are in the Home Directory. To do this, we need to type ‘dir’, followed by pressing the Enter key on the keyboard.

dir command

Folder and files are case sensitive in Linux, so if we are searching for something specific, we need to ensure it is spelt exactly the same or it will ignore it.
I want to create a file in the ‘Documents’ folder. This can be done by typing ‘CD Documents’.

CD Documents

Using the ‘CD Documents’ command has opened that directory, however, I’m not sure if the file that I’m looking for is saved here or not. To find this out, I’m going to need to list everything that is in the Documents folder. Type the command ‘ls’. Short for ‘list’, this will show whether the file I’m looking for is there or not.

ls command

I was looking for the Python file labelled ‘file.py’, it was saved in this folder after all.
Now that the file has been found, I can continue working on it. By using the command ‘vim file.py’, I can work on the file in the terminal.

Vim file.py

To work on the file, press ‘I’ to put Vim into ‘insert’ mode, allowing changes to be made to the file. After making the changes to the document that needed to be made. Its time to save and exit. To exit Vim type, :wq!
This will save and quit Vim taking us back to the terminal window. Now that we have finished working in the terminal, type ‘exit’ to quit.

Working in Vim

Adjust Screen Resolution for an Ubuntu Hyper-V Virtual Machine

For a while I’ve been using Ubuntu 20.10 as a machine that I setup to run in Hyper-V. However, the default screen resolution of a virtual machine package is 1024×768.
Whilst this is all well and good for short term use, it can become quite tiresome and cause considerable eye strain with long-term use.
Good News! With a few simple commands in the terminal, this setting can be changed to a more suitable resolution.
Firstly, open the terminal and enter the following command:

Sudo vim /etc/default/grub

Sudo or root privileges are required to run this, otherwise the grub file opens as Read-Only and cannot be changed. Press ‘i’, this will change vim to ‘insert’ mode and allow changes to be made.
There are two lines in the grub file that need to be updated for the resolution changes to take effect.
Locate ‘grub_cmdline_linux_default=’ and ‘grub_cmdline_linux=’. Once you have found those two lines, which are located directly next to each other; update the end of each entry to add “quiet splash video=hyperv_fb:1920×1080”.
Change the resolution at the end to meet your requirements.

“quiet splash video=hyperv_fb:1920×1080”

After updating the file, press ‘esc’ followed by ‘:wq!’ (without the quotation marks), this will close vim whilst writing and saving the changes.
To complete the changes to the file, it is now time to update grub. This can be done by using the command ‘sudo update-grub’.

sudo update-grub

All the necessary sections have been updated, next time the machine reboots, it will reboot with the new resolution in place.

Ubuntu VM after grub update

Using Lists in Python

Why use lists in Python?
Lists are used in Python to assign multiple values to a single variable. Lists are one of four arrays that exist in Python, the other three are called ‘Sets’, ‘Tuples’ and ‘Dictionaries’. Lists are identified by their square brackets. The reason to use Lists is that they are mutable. This means that a list can be changed to include other items or that items can be removed from the list altogether. There are several functions that can be called upon to determine the length of a list, or to add/remove additional items which I will now discuss.

Lists

I have created a list of fruits. At the moment the list only contains three items, which isn’t very exciting. We’re going to add more content to this list by using the append() function.
Append() can only be used to add one item at a time, so to add more items we’d need to use append() several times.

Append()

The len() function can be used to determine how many items are in a list. Its possible that in a big project you would have multiple lists, so use the len() statement in a print function with the name of the list you wish to examine.

Len()

An important thing to remember, is that numbering in Python always starts at zero. This makes the first item in a list ‘zero’.
Whilst len() can report back on every item in a list, it can also be used to count the length of an individual item in a list. Using the print statement we used in the screenshot above, at the end of ‘fruits’ add in square brackets and the item in the list that you wish to count to return the length of that item in the string.

len(fruits[3])

If we were to run the code ‘print(len(fruits[3]), it would return the value ’10’. This is because ‘Strawberry’ is the fourth item on the list and consists of ten letters.
Lists are not limited to strings. Any data type can be called from a list, whether it be a string, integer, float or Boolean data type.

Data Types

Similar to how len() function works by printing the length of an individual item in a list, the string can be called in the reverse order by using [::-1] at the end of the list name in print operator.            

Reverse a string

This is just a brief example of some of the things that lists can do. The best way to learn more about lists is to practice using them in your code.

Challenges

  • Can you find how to insert items into the middle of a list?
  • Can you write a function to count how many times a single letter occurs in a list?

Which IDE/Text Editor for Python Development?

There are a number of great options available when it comes to programming anything in Python, or indeed any programming language.
If you are using a Windows machine for Python, you will no doubt have Idle installed as this is bundled in with the installer.
Idle offers many great features, in that it has a ‘code as you go’ area and type in basic programs to test out code. However, if you wanted to write more complex code, the option is there. Selecting File > new, opens a text editor similar to notepad with the added addition that any keywords are colour coded. 

Idle
Idle Text Editor

Whilst I would consider Idle great for beginners, there are Integrated Development Environments that exist to make workflow more seamless. For example, Visual Studio provides the ability to write Python code and upload it straight to Github. For larger projects, this can be incredibly helpful to update a project in seconds, instead of having to switch between multiple applications.
One of the downsides to working with Visual Studio is that Python functionality is not enabled by default. It must be added as an extension from the store.

Visual Studio

 Another example of a great IDE is PyCharm.
Pycharm is optimised for Python Development. Similar to Visual Studio, Pycharm has includes the Terminal and a Python console in one place so that the code can be run directly from the application. An addition to Pycharm is that when the application is opened it provides a ‘tip of the day’. The option exists to turn off the notifications, however, I have left it on as it is providing some useful tips that I can apply to my coding journey.

Pycharm

I have only been coding for about ten weeks, so this is a fairly limited review and doesn’t cover the full functionality and possibilities that these applications provide. It is also the reason; I am not including more examples within this blog post.
There is one more application that I have used briefly that I would like to make mention of, and that application is Vim within the Linux Terminal.
Vim has a steep learning curve and can be difficult to get grips with at first, however, with more use the easier it becomes.

Vim Editor

There are other IDE’s and text editors available. Be sure to do some research and find the one that works for you and makes your workflow just a little bit easier.

Creating a Random Character Generator using Python

Following on from the creation of Rock, Paper, Scissors last week where we used the random module to create random plays by the computer. Today, we are going to use random again to create a randomly generated string of text, much like those of random password generators that are used by Password Management Systems.
When the program runs, it should look something like this:

Program Output

To begin, we need to import the random module, from there we need to define the variable that will be used to shuffle the string of text so that it will produce something different every time.

Defining Shuffle

There are several parts to this variable. It needs to start by defining what it is going to be doing, in this case, it will be shuffling the randomly generated string of text.
The ‘return ‘ ‘.join(generate) is important in the way that it is written. This will join all the characters of the string together. The middle of the ‘ ‘ needs to remain blank, as this determines what will link the tuple together when the program is run.
For example, if that line is changed to look like this: ‘#’.join(generate), the program will put a hash in between each character, as shown in the screenshot below.

Hash Outcome

Alternatively, if a space is left between those two characters, when the program is run, everything will have a space between it instead.
Now that we have defined the shuffle function within the program, it is time to create the variables that will be included within the string.
For this section, I am using two of everything. Two uppercase letters, two lowercase, two numbers and two special characters.

An ACSII code chart is needed to plot what is returned by each variable.

  • Numbers 65 – 90 will print uppercase letters
  • Numbers 97 – 122 will print lowercase letters
  • Numbers 48 – 57 will print numbers between 0 and 9

Random symbols are harder to plot as they are dotted about between the upper and lowercase characters on the chart. That is why, the random symbols variables have two different sets of numbers applied to them.
The randint method is added to the variable so that the computer will choose a different setting every time.

When all the variables have been created, they need to be linked together, so that they can be assigned to a print statement.
It is time to call upon the shuffle function, otherwise everything listed will just print in that order.

Password Variable


Finally, add in a print statement and the program is complete.

Print Statement

It occurred to me as I was writing this, that I could reduce the size of the program but still make the outcome work in the same way. To do this, I removed some of the excess variables from the program, as shown in the screenshot below.

Updated Main Body

This in turn, made listing the variables cleaner and less plus symbols to combine them all together. In addition to reducing the number of variables, I multiplied the password by two, which increased the length of the string but still kept it random and didn’t just duplicate the same string.


I hope that you have enjoyed reading through and perhaps trying this out for yourself. As an additional challenge, why not try building on this by editing the text further still, or by getting this to display on a GUI pop-up.

BMI_Calculator.py

BMI Calculator Script

I have been playing around with if and elif statements and created this BMI Calculator.
There are a few different elements that needed implementing to get this to work properly.
Firstly, the program needs variables creating that will take input from the person using the program. I have used a mixture of integers and floats. However, it is best to use a float to enable the user to enable a decimal place.
To calculate the BMI output the weight input needs to be multiplied by 703 and divide that number by height in inches squared.
The program needs to be completed with if and elif statements to give a predetermined output, ranging from ‘underweight’ to ‘obese’.
I have ended the program with a print statement that states any BMI outputs should be used as a guide only.

BMI Output

Creating ‘Rock, Paper, Scissors’ using Python

In order to create ‘Rock, Paper, Scissors’ we’re going to need to make use of the loop functions that are available in Python.

Firstly, we are going to need to call upon the ‘random’ module which will allow us access to the ‘randint’ method. I will explain why this is important, a bit later.

from random import randint

Once we have defined which module is going to be needed, it is time to create the variables needed to play the game. In this scenario, I have labelled the variable ‘g’ for game, but you can define it any way that works for you. We can add multiple values in this by use of square brackets and separating each variable with a comma.

List variable

Now that we have our variables, it is time to create the players. We are going to start with creating the computer, as that is who we will be playing against. When creating the Computer, we will need to combine ‘randint’ so that a random play can be chosen from the list. As was done with the list, randint is encased in square brackets, with ‘0,2’ in curly brackets. In Python all operators start at zero.

In this instance:

Zero = Rock
One = Paper
Two = Scissors

Computer

When the Computer has been set, its time to add the Player. In this case, I have set the variable as my name. It really makes no difference what you label the variable, so long as you are consistent throughout otherwise, the program will run into errors. The player value needs to be set to ‘False’. The reason for this is when the game starts, the operator will automatically change to ‘True’ allowing the While loop to run.

Player

Now that all the variables have been set, it is time to move onto the main body of the program. Inside the ‘While Loop’ are nested ‘if’ and ‘elif’ statements which control the various outcomes of the game. It is important to define the tie breaker early on and then defining the reasons that the game resulted in either a Win, Loss or Draw.

As you will be able to see from the following screenshot, I have added ‘\n’ at the end of the user input. This will end the string on a new line and makes the overall responses within the game easier to read.

Finally, at the end of the ‘While Loop’, it is important to add an else statement for an invalid play. This will allow the game to continue if an incorrect value is entered by the user.

While Loop

Two more lines of code are required at the end of the While Loop. These two lines are required, so that the game will run from one instance to the next in an infinite loop.

The player variable needs to be set back to ‘False’ at the end of the play for this to occur, and the computer is listed here for the same reason, so that it will continue to be assigned random plays.

Infinite Loop

For any fans of the Big Bang Theory, I am hoping to try and expand on this code to create a ‘Rock, Paper, Scissors, Lizard, Spock’ game, but first I had to work through this code to understand how it should work. In addition to this, I want to try and build on it further by adding a graphical interface.

I also want to say that I got the code for this game from this website, they have a lot of great tutorials and content for anybody learning Python.

Creating Mad Libs using ‘F-strings’

What is F-String?
An F-String is a formatting concept that allows us to call upon Python functions within strings of text. F-string stands for ‘Formatted string’.  The use of F-string is only available in Python version 3.6 and above. Previously to this, you would have had to use .format() instead. A more up to date version of Python can be downloaded from https://www.python.org

To create a Mad Lib using an F-string, we first need to create a couple of variables that will be used in our string of text. In this example we’re going to be using two variables. A subject and a noun.

Creating Variables

Once the variables have been created, it is time to implement the ‘f-string’. F-strings are easy to spot within the program, as they always start with a letter ‘f’ and the string of text that follows is in speech marks or single quotes. Like so: mad_lib = f”string of {subject}”

Mad_lib

The curly brackets ‘{}’ are required to import the variable that was created earlier. When the program is run, the curly brackets will be replaced by the text the user entered.

Finally, to run the program, a regular print statement is needed.

Print Statement

If everything has been written correctly, and no errors have been reported. When the program runs, the output should look something similar to the image below.

If you are using a version of Python that is older than 3.6. You can create a similar program, however, its layout will look slightly different.

Format String

The ‘.format()’ approach will still work if you are using a version of Python that is later than 3.6. It differs from ‘f-string’ in that the curly brackets are left blank and that they are specified at the end of the string. Once the variables have been created, they can be used in any order. Simply by putting: .format(subject, name) would change the layout of the sentence.

Format Output

It doesn’t matter which version you use to create the Mad Lib. Both of the program’s outputs are identical achieve the same goal.