You have found your next IT professional

Tag: Python

Reaction Time Tester

Brief

The brief for this exercise was to create a reaction time tester with a graphical interface. It proves to be a good exercise to learn about the tkinter module

import time
import random
import tkinter as tk

# Initialize the window
root = tk.Tk()
canvas = tk.Canvas(root, width=360, height=640, bg="white")
canvas.pack()

# Create the square and bind the click event
black_square = canvas.create_rectangle(80, 240, 280, 440, fill="black")
start_time = 0
reaction_text = None
best_time_text = None

# Create a best time
best_time = float('inf')  # Initialize with infinity

def update_square(event):
    global start_time, reaction_text, best_time, best_time_text
    end_time = time.time()
    reaction_time = round(end_time - start_time, 4)
    canvas.itemconfig(black_square, fill="black")
    if reaction_text is not None:
        canvas.delete(reaction_text)
    reaction_text = canvas.create_text(180, 500, text=f"Reaction Time: {reaction_time}s", font=("Calibri", 18), fill="black")
    
    if reaction_time < best_time:
        best_time = reaction_time
        if best_time_text is not None:
            canvas.delete(best_time_text)
        best_time_text = canvas.create_text(180, 600, text=f"Best time: {best_time}s", font=("Calibri", 12), fill="black")
    
    root.update()
    root.after(6000, initialize_app)  # reset after 6 seconds

def show_green():
    global start_time
    canvas.itemconfig(black_square, fill="green")
    start_time = time.time()

def initialize_app():
    global reaction_text, best_time_text
    # Clear the canvas
    canvas.delete("all")
    
    # Recreate the square
    global black_square
    black_square = canvas.create_rectangle(80, 240, 280, 440, fill="black")
    
    # Draw the title and instructions
    canvas.create_text(180, 100, text="Reaction Time Tester", font=("Calibri", 18), fill="black")
    canvas.create_text(180, 200, text="Click on the square when it turns green.", font=("Calibri", 12), fill="black")
    
    # Display the current best time
    best_time_text = canvas.create_text(180, 600, text=f"Best time: {best_time:.4f}s", font=("Calibri", 12), fill="black")

    # Bind the click event
    canvas.tag_bind(black_square, "<Button-1>", update_square)

    # Clear the previous reaction time text
    reaction_text = None

    # Wait a random interval between 2 to 4 seconds, then turn the square green and start the timer
    root.after(2000 + random.randint(0, 2000), show_green)

# Initialize the app and start the main loop
initialize_app()
root.mainloop()

Imports

Three modules are imported. time, random and tkinter. tkinter is for the graphical interface and random and time are used together to create the core function of the app.

Initialise The Window

# Initialize the window
root = tk.Tk()
canvas = tk.Canvas(root, width=360, height=640, bg="white")
canvas.pack()

This initialises a Tkinter window and creates a canvas within it. The window is the main application container, while the canvas is a drawing area. The canvas is set to 360×640 pixels with a white background. The canvas is then packed into the window, making it visible and ready for drawing or adding other elements.

Create The Square

# Create the square and bind the click event
black_square = canvas.create_rectangle(80, 240, 280, 440, fill="black")
start_time = 0
reaction_text = None
best_time_text = None

This code creates a black square on a canvas. It sets up variables to track the start time, and variables for displaying reaction time and best time. The square will be the target for user clicks, initiating the timing mechanism when interacted with.

Create a Best Time

# Create a best time
best_time = float('inf')  # Initialize with infinity

Here we initialise a variable called ‘best_time’ with positive infinity. In Python, float(‘inf’) represents infinity. This is a common technique used when you want to find the minimum value in a set of numbers. By starting with infinity, any real number will be smaller, allowing you to update ‘best_time’ as you compare values.

Define Update Square Function

def update_square(event):
    global start_time, reaction_text, best_time, best_time_text
    end_time = time.time()
    reaction_time = round(end_time - start_time, 4)
    canvas.itemconfig(black_square, fill="black")
    if reaction_text is not None:
        canvas.delete(reaction_text)
    reaction_text = canvas.create_text(180, 500, text=f"Reaction Time: {reaction_time}s", font=("Calibri", 18), fill="black")
    
    if reaction_time < best_time:
        best_time = reaction_time
        if best_time_text is not None:
            canvas.delete(best_time_text)
        best_time_text = canvas.create_text(180, 600, text=f"Best time: {best_time}s", font=("Calibri", 12), fill="black")
    
    root.update()
    root.after(6000, initialize_app)  # reset after 6 seconds

This function updates the game state after a player clicks the square. It calculates the reaction time, updates the display with the current time, and checks if it’s a new best time. The function then resets the game after a 6-second delay. Key actions include:

  1. Calculate reaction time
  2. Update square color
  3. Display reaction time
  4. Update best time if applicable
  5. Schedule game reset

The function uses global variables to maintain state across multiple function calls and interacts with a canvas object to update the visual elements of the game.

Define Show Green Function

def show_green():
    global start_time
    canvas.itemconfig(black_square, fill="green")
    start_time = time.time()

Now we define the function that turns the square to green which is the signal to the user that the timer has started and they should click on the square asap. The global variable start_time is used to record the start of the timing.

Define the Initialise App Function

def initialize_app():
    global reaction_text, best_time_text
    # Clear the canvas
    canvas.delete("all")
    
    # Recreate the square
    global black_square
    black_square = canvas.create_rectangle(80, 240, 280, 440, fill="black")
    
    # Draw the title and instructions
    canvas.create_text(180, 100, text="Reaction Time Tester", font=("Calibri", 18), fill="black")
    canvas.create_text(180, 200, text="Click on the square when it turns green.", font=("Calibri", 12), fill="black")
    
    # Display the current best time
    best_time_text = canvas.create_text(180, 600, text=f"Best time: {best_time:.4f}s", font=("Calibri", 12), fill="black")

    # Bind the click event
    canvas.tag_bind(black_square, "<Button-1>", update_square)

    # Clear the previous reaction time text
    reaction_text = None

    # Wait a random interval between 2 to 4 seconds, then turn the square green and start the timer
    root.after(2000 + random.randint(0, 2000), show_green)

This function initialises the reaction time test. It clears the canvas, creates a black square, displays instructions, and shows the best time. It then sets up a click event on the square and schedules the square to turn green after a random delay of 2-4 seconds. This prepares the game for a new round, resetting the display and setting up the next test.

Function Calls

initialize_app()
root.mainloop()

The initialize_app function is called which is the core of the program and the mainloop method is called on the root that starts the event loop for the GUI. It listens for user interactions (like button clicks) and keeps the window open.

Conclusion

There we have it. A simple GUI python program for testing how slow or fast your reactions are.

Creating a Weather App in Python

How to create a very simple weather app in Python. In this tutorial, we will use the requests module to retrieve weather data from the OpenWeatherMap API and the tkinter module to build a simple GUI for our weather app.

Let’s get started!

Concept Weather App

Step 1: Setting up the environment.

First, we need to set up the environment for our project. We will be using Python 3, so make sure you have it installed on your computer. You can download it from the official website here.

Next, we need to install the requests module. To do this, open your terminal and run the following command:

pip install requests

We also need to install the tkinter module. If you’re using Python 3 on Windows or macOS, this should be installed by default. If you’re using a Linux distribution, you may need to install it separately. For example, on Ubuntu, you can install it by running the following command:

sudo apt-get install python3-tk

If you use an IDE such as Pycharm then it will give you the option of installing modules that you attempt to use but haven’t yet installed. Very handy.

Step 2: Register for OpenWeatherMap API Key.

Next, we need to register for an API key with OpenWeatherMap. To do this, go to their website here and create an account. Once you’ve created an account, log in and go to your API keys page. Create a new API key and copy it to your clipboard.

Step 3: Writing the code.

Now that we have everything set up, let’s start writing our code.

We’ll start by importing the necessary modules and defining a function to retrieve weather data from the OpenWeatherMap API.

Python code for getting weather data from an API

In this function, we specify the API endpoint and API key for OpenWeatherMap, and the location for which we want to retrieve weather data. We make a GET request to the API with these parameters, and check the status code of the response to make sure it was successful. If it was, we return the weather data as a JSON object. If not, we print an error message and return None.

Next, we’ll create a window for our weather app using the tkinter module.

Creating a window for a weather app using the tkinter module in Python

In this code, we create a new window with the title “Weather App”. We then create a label with the text “Enter Location:” and an entry widget for the user to input the location they want to retrieve weather data for.

We also create a button labelled “Submit” which will call the get_weather function with the location entered by the user.

Finally, we create a label to display the weather data retrieved from the API. We can now define the get_weather function to update the weather label with the current temperature for the given location.

Defining a function in Python

In this function, we call the get_weather_data function to retrieve weather data for the given location. If the function returns weather data, we update the weather label with the current temperature for that location.

We subtract 273.15 from the temperature value to convert it from Kelvin to Celsius. If the get_weather_data function returns None, we update the weather label with an error message.

Finally, we run the main loop of the tkinter application.

root.mainloop()

This will start the application and display the window we created.

Step 4: Putting it all together.

Now that we’ve written all the necessary code, put it all together in the order we have here.

Make sure you replace YOUR_API_KEY_HERE with the API key provided from OpenWeatherMap.

Once you have done that it is time to run the code!

Weather App. Progrrammed in Python.

Conclusion

In this tutorial, we’ve learned how to use the requests and tkinter modules in Python to create a weather app. We’ve used the OpenWeatherMap API to retrieve weather data for a specified location and displayed the current temperature in Celsius using a GUI built with tkinter. This is just a basic implementation and there’s a lot more that could be done to improve the app. For example, we could add more weather information, allow the user to specify units, or even display a forecast for the next few days.

I hope this tutorial was helpful and you were able to create your own weather app.

Concept of programming an app.

Creating Sockets In Python

Python is a powerful and versatile programming language that is well-suited to many different tasks, including network programming. In this post, we’ll show you how to use Python to create a socket connection between a server and a client.

Before we do anything I would like to point out that it is recommended to try this on a single machine which acts as both the server and the client. Telusko does this in his tutorial https://www.youtube.com/watch?v=u4kr7EFxAKk and it makes life much simpler as you are not having to fight firewalls and more if you try and connect to a VM in the cloud for example.

With that said, let’s take a look at the server-side code. Here is an example of a simple Python server that listens on a specific port and returns a message to any client that connects to it:

import socket

# Create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to a specific address and port
s.bind(("localhost", 12345))

# Listen for incoming connections
s.listen(5)

while True:
    # Establish a connection with the client
    c, addr = s.accept()
    print("Got connection from", addr)

    # Send a message to the client
    c.send(b"Thank you for connecting")

    # Close the connection
    c.close()

In this example, we first import the socket module, which provides all the necessary functions for working with sockets in Python. Next, we create a new socket object using socket.socket() and specify the address family (AF_INET) and socket type (SOCK_STREAM). These specify IPv4 and TCP respectively. (You can in fact leave these out as they are the default settings.)

We then use the bind() method to bind the socket to a specific address and port. In this case, we’re binding to “localhost” (which refers to the local machine) and port 12345. Don’t use a port in the 1-1000 range as it will probably be busy.

Next, we use the listen() method to start listening for incoming connections. The argument to this method specifies the maximum number of queued connections.

The while loop is used to accept incoming connections, using the accept() method. This method returns a new socket object representing the connection, as well as the address of the client. We use the send() method to send a message to the client, and then close the connection using the close() method.

Now let’s take a look at the client-side code. Here is an example of a Python client that connects to the server and sends a message:

import socket

# Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to the server
client_socket.connect(('localhost', 1234))

# Receive data from the server
data = client_socket.recv(1024)
print(f"Received data: {data}")

# Close the client socket
client_socket.close()

This client code is similar to the server code, but with some important differences. First, instead of calling bind() and listen(), we call connect() to connect to the server. We then use the send() method to send a message to the server, and the recv() method to receive data from the server. Finally, we close the connection using the close() method.

Simple ASCII Converter

while True:
    x = (input("Enter character or ASCII value for conversion or q to quit: "))
    if x == "q":
        break
    if len(x) > 1 and not x.isdigit():
        print("not applicable: fail")
        break
    elif x.isdigit():
        print(chr(int(x)))
    else:
        print(ord(x))

So you are relatively new to programming, like me, and you have got a few concepts under your belt. Probably you are bored of print(“Hello world!”). You are looking for a basic program to write. Something that is actually relevant to IT.

While I was going over notes from the Programming Expert course, I was messing around with a while loop and ASCII conversion functions ord and chr. If you are not familiar with ASCII then just know that it is a numerical value given to each symbol/character we use in computing. So a = 97, A = 65, # = 35 and so on.

The Crux of the Matter

print(ord(x)) 

will print the ASCII value of the variable x

print(chr(x))

will print the character of the variable x

These are the active ingredients of this little program. Let’s look at the rest of it:

Line 1: Creates an infinite loop. In which we will put our block of code.

Line 2: Asks the user to input a number or character and puts this in the variable x. It also gives the user the option to quit the infinite loop.

Line 3+4: Enables the quit feature.

Line 5+6+7: Input validation. The ord and char functions are a bit fussy and will only take an integer or a single character respectively. So this if statement effectively says that if the length of the input is greater than one character and is not a digit then it’s no good and the user is told as much. (Note that even if a float is entered then this will be more than one character and will fail too.)

Line 8/9: The next part of the if statement is an elif which asks if x is a digit then print the character associated with the value. It has been converted from the string the user entered, to an integer which the function can read.

Line 10/11: Anything else must be a single character and is then converted to a value.

And there you have it. Admittedly this is a simple converter which only accepts one input at a time and can’t deal with [DELETE] for example but it’s still pretty neat. I am finding it’s important to gain confidence at coding by experimenting with small programs.

Programming Expert

Recently started a new course called Programming Expert.

Coding is not essential for an IT career but it sure as helps and although intimidating it is also fascinating. Getting a program to work for the first time is a buzz. If you intend to go into Cyber Security then you definitely need some coding skills and Python is a great language for this and also is beginner friendly.

I tried the usual YouTube offerings:

(too name just a few) for learning to code and no doubt this is absolutely a viable option but it is hard to get a structure to your learning going this way. So I signed up to an official course from a group of programmers including Tim Ruscica.


It was $59 for a year from the videos I’ve watched on his YT channel his style came across as easy to follow and he clearly knows what he’s talking about. In my opinion if you are going to be listening the same person for hours while they try and teach you to code, surely a experience which will get you frustrated at times, then you need to get on with their general style.

More importantly this course boasts the following features:

  • Streamlined Platform
  • A Comprehensive Curriculum
  • Designed By Experts. Taught By Experts
  • High-Quality Videos
  • Hundreds Of Practice Questions
  • Practical Programming Projects
  • Feature-Rich Coding Workspace
  • Certificate Of Completion

These add up to an experience which is on another level compared with trying to learn from a “Learn Python in 6 Hours” video. For example on the more challenging Practice Questions (most of them) there’s not just the solutions revealed but also a separate video to explain how to solve the problem.

I am halfway through the fundamentals stage and will post updates as I go.

© 2025 timnott-it

Theme by Anders NorénUp ↑