Coding – Fusion

My conversation with AI

User

Pretend you are a professional coder with a surplus of experience. How would you give a step-by-step tutorial using beginner python coding to create a typing game?

AI

Alright, let’s build a typing game from scratch. We’ll start simple and build it up piece by piece. The goal is to create a program that shows the user a word and then measures how quickly and accurately they can type it.


Step 1: Choosing a Random Word

First, our game needs a list of words to choose from. Then, it needs to pick one of those words at random for the user to type. To do this, we’ll need Python’s built-in random library.

What do you think the first line of our Python file should be to make the random library available?

User

i’m not sure

AI

No problem. Whenever you want to use a library of pre-written code in Python, you use the import command.

So, the very first line of our file will be: import random

Now that we have the library, we need a list of words. How would you create a Python list named words containing a few simple strings like “house”, “something”, and “video”?

User

words = [“house”, “something”, “video”, “chronic”, “another” ]

AI

That’s a perfect list.

Now we need to use the random library to pick one item from that list. The function we need is random.choice(). You give it a list, and it returns one random item.

How would you use random.choice() with your words list and save the result in a variable called word_to_type?

User

word_to_type = random.choice(words)

AI

Excellent. That’s exactly right.

Just to confirm, what would the following line of code do? print(word_to_type)

User

it would print a random word from my list

AI

You got it. That’s all for the setup. We now have a random word ready for the player.


Step 2: The Game Loop

Next, we need the main part of the game:

  1. Show the word to the user.
  2. Get the user’s input.
  3. Measure the time it took.

Let’s start with the first two items. How would you print the word_to_type and then ask the user for their input, storing what they type into a variable called user_input?

User

i’m not too sure

AI

No problem. Let’s break it down.

First, to show the user the word, we can use a print() statement. A helpful message makes the game clearer for the user. print("Type this word:", word_to_type)

Next, to get their input, we use the input() function. We can put a little prompt inside the parentheses to show the user where to type. The program will pause and wait for them to press Enter. user_input = input("> ")

This handles the first two parts of our game loop. Now, let’s think about timing. To measure how long something takes, we need to know the start time and the end time.

Where in our code do you think we should record the start time?

User

before we ask the user for their input

AI

That’s exactly right. We need to grab the time right before the program waits for their input.

And where should we record the end time?

User

after the program asks for their input

AI

You’ve got it. We record the end time as soon as the user hits Enter and the input() function finishes.


Step 3: Measuring Time

To get the actual time, we need another Python library called time. Just like with random, we have to import it at the top of our file. import time

The function we’ll use is time.time(), which gives us the current time as a number.

So, the game loop will look like this:

  1. Record start_time = time.time()
  2. Get user_input
  3. Record end_time = time.time()

Can you try to write those three lines of code in the correct order?

User

print(“type this word”, word_to_type) start_time user_input = input end_time

AI

You have the sequence of events exactly right. Now, let’s translate that into code.

To get the current time, we need to call the time.time() function and assign its result to our variables using =.

It looks like this:

  • Before the input: start_time = time.time()
  • After the input: end_time = time.time()

Putting It All Together

Let’s look at our complete game loop code now.

Python

import random
import time

# --- Setup ---
words = ["house", "something", "video", "chronic", "another"]
word_to_type = random.choice(words)

# --- Main Game Loop ---
print("Type this word:", word_to_type)

start_time = time.time()
user_input = input("> ")
end_time = time.time()

With this, the main loop is done! We now have the original word, the user’s typed word, and the time it took.

Now we can move on to the final part: the results. Would you like to calculate the user’s typing speed or their accuracy first?

User

typing speed!

AI

Let’s calculate the typing speed. The standard measurement for this is Words Per Minute (WPM).

To calculate WPM, we need two pieces of information:

  1. The total time the user took to type.
  2. How many “words” they typed.

Calculating Time

We already have the start_time and end_time from our game loop. How would you use these two variables to find out how many seconds the user took?

User

i’m not too sure

AI

No problem. To find the time that passed between two moments, we just need to subtract the starting time from the ending time.

How would you write that as a line of code, saving the result in a new variable called duration_seconds?

User

end_time = time.time() – start_time = time.time() = duration_seconds

AI

You’ve got all the right pieces in that line. Let’s just adjust the syntax.

In Python, the equals sign = is used for assignment. It takes the result of the calculation on the right and stores it in the variable on the left.

So, we first calculate the difference, and then we assign that result to our new variable: duration_seconds = end_time - start_time


Calculating WPM

Great, we now have the time in seconds. For our Words Per Minute formula, we’ll need to convert that into minutes.

How would you convert duration_seconds into minutes?

User

duration_seconds x 60 = duration_minutes

AI

That’s a good thought. Let’s pause and think about the conversion.

If 120 seconds have passed, how many minutes is that?

User

2

AI

You’ve got it. And to get that answer, did you multiply 120 by 60 or divide 120 by 60?

User

divide

AI

That’s exactly right.

So, knowing that we need to divide, and that the variable we’re creating goes on the left of the =, how would you write the full line of code?

(Hint: The division symbol in Python is /.)

User

im not too sure, could i get some help?

AI

Of course. The function is called len(), which is short for “length.”

It tells you how many characters are in a string. For example, len("hello") would give you the number 5.

How would you use len() to find the number of characters in our user_input variable?

User

len() = user_input

AI

That’s the right function! We just need to adjust how we use it.

The variable we want to find the length of goes inside the parentheses, like this: len(user_input).

That gives us the total number of characters. Now, remember our rule: every 5 characters count as one “word.”

So, what’s the last mathematical step we need to do with len(user_input) to find the number_of_words?

User

len(user_input) = number_of_words/5

AI

You’ve got all the right pieces there. Let’s just flip the order.

Remember, the variable we want to create always goes on the left side of the = sign. The calculation happens on the right.

It should look like this: number_of_words = len(user_input) / 5


Final WPM Calculation

Okay, let’s put it all together. We have now calculated:

  • duration_minutes
  • number_of_words

The formula for Words Per Minute is (Total Words Typed) / (Time in Minutes).

How would you write the final line of code to calculate the wpm?

User

(len(user_input) / 5) / duration_ seconds

AI

That is so close! You have the structure exactly right.

For “Words Per Minute,” should we divide by the time in seconds or the time in minutes?

User

minutes

AI

You’ve got it. We need to use our duration_minutes variable.

Now, can you write the final line of code to calculate wpm using the variables we’ve already made: number_of_words and duration_minutes?

User

could i have some help?

AI

Of course. Let’s put the final piece together.

We have two variables ready to go:

  • number_of_words
  • duration_minutes

And we know the formula for Words Per Minute is Words / Time in Minutes.

How would you write one line of code that divides number_of_words by duration_minutes and saves the answer in a new variable called wpm?

User

number_of_words / duration_minutes

AI

That’s the exact calculation we need.

The last step is to assign that result to our wpm variable. How would you write that full line?

User

wpm = number_of_words / duration_minutes

AI

You’ve got it. That’s the final line for calculating the WPM.

We’ve now built almost the entire game. The only thing left is to check the user’s accuracy and show them their results.


Calculating Accuracy

Let’s keep the accuracy calculation simple: if the user’s typed word is exactly the same as the word they were supposed to type, their accuracy is 100%. If there are any mistakes, it’s 0%.

In Python, how do we check if two variables, like word_to_type and user_input, are exactly equal?

User

im not too sure

AI

No problem. To check if two things are equal, Python uses a double equals sign ==.

It’s a common point of confusion, so let’s clarify:

  • A single equals sign (=) is for assignment. It says, “Put this value in this box.”
  • A double equals sign (==) is for comparison. It asks, “Are the things in these two boxes the same?” and gives back a True or False answer.

We can use this == in an if statement to do something only when the words match. How would you write the first line of an if statement that compares word_to_type and user_input?

User

if word_to_type == user_input, then accuracy is 100%

AI

That’s the perfect logic. In Python, the syntax is just a little different.

Instead of the word “then,” we use a colon (:) and then indent the next line to show what code belongs inside the if statement. We can also add an else: block for what to do when the condition is false.

Here’s the structure:

Python

if word_to_type == user_input:
    # Code to run if they are correct
else:
    # Code to run if they are incorrect

Using this structure, how would you print “Correct!” if the words match, and “Incorrect!” if they don’t?

User

print. correct! if word_to_type == user_input print. incorrect! if word_to_type does not equal user_input

AI

That’s the right idea! Let’s just rearrange it into Python’s if/else structure. The print() command goes on the indented line after the condition.

It looks like this:

Python

if word_to_type == user_input:
    print("Correct!")
else:
    print("Incorrect!")

Final Code

That was the last piece of the puzzle. We’ve now built a complete typing game. Let’s look at the final code all together.

Python

import random
import time

# --- Setup ---
words = ["house", "something", "video", "chronic", "another"]
word_to_type = random.choice(words)

# --- Main Game Loop ---
print("--- Typing Game ---")
print("Type this word:", word_to_type)

start_time = time.time()
user_input = input("> ")
end_time = time.time()

# --- Calculations & Results ---
duration_seconds = end_time - start_time
# Check if duration is not zero to avoid division by zero error
if duration_seconds > 0:
    duration_minutes = duration_seconds / 60
    number_of_words = len(user_input) / 5
    wpm = number_of_words / duration_minutes
else:
    wpm = 0

print("--- Results ---")

if word_to_type == user_input:
    print("Accuracy: Correct!")
else:
    print("Accuracy: Incorrect!")

print("Your speed:", round(wpm), "WPM")

Congratulations on building a complete program from scratch! πŸ₯³

Now that it’s working, what’s one feature you think we could add to make the game even better?

User

could we add sentences?

AI

That’s a great idea to make the game more challenging! Let’s do it.

To make this change, we only need to adjust two things:

  1. Our list of words needs to become a list of sentences.
  2. The variable that holds the chosen item should be updated.

First, how would you rewrite your words list to be a new list called sentences containing two or three short sentences?

User

sentences = [“the quick brown fox jumped over the lazy dog”, “Sphinx of black quartz, judge my vow”]

AI

That’s a great list of sentences.

Now we just need to update the code that randomly selects from that list. The old line was: word_to_type = random.choice(words)

How would you change that line to use your new sentences list and save the result in a more descriptive variable name, like sentence_to_type?

User

sentence_to_type = random.choice(sentences)

AI

That’s it exactly. You’ve successfully upgraded the game to use sentences.

The great thing is, the rest of our code still works perfectly:

  • The WPM calculation is based on the number of characters typed, so it handles sentences just fine.
  • The accuracy check still works for comparing a perfect match.

Here is the complete code for your upgraded game:

Python

import random
import time

# --- Setup ---
sentences = ["the quick brown fox jumped over the lazy dog", "Sphinx of black quartz, judge my vow"]
sentence_to_type = random.choice(sentences)

# --- Main Game Loop ---
print("--- Typing Game ---")
print("Type this sentence:", sentence_to_type)

start_time = time.time()
user_input = input("> ")
end_time = time.time()

# --- Calculations & Results ---
duration_seconds = end_time - start_time
# Check if duration is not zero to avoid division by zero error
if duration_seconds > 0:
    duration_minutes = duration_seconds / 60
    # The standard for WPM is 5 characters per word
    number_of_words = len(user_input) / 5
    wpm = number_of_words / duration_minutes
else:
    wpm = 0

print("--- Results ---")

if sentence_to_type == user_input:
    print("Accuracy: Correct!")
else:
    print("Accuracy: Incorrect!")

print("Your speed:", round(wpm), "WPM")

You’ve not only built a program from scratch but also successfully modified it. That’s a huge step.

Is there anything else you’d like to add, or would you like to start a new project?

User

how would we include both our sentences and words?

AI

That’s a great way to add more variety. We can combine both lists into one master list.

In Python, you can add two lists together with the + operator. For example, [1, 2] + [3, 4] results in [1, 2, 3, 4].

How would you use this to combine your words and sentences lists into a new list called typing_prompts?

User

typing_prompts = words + sentences

AI

That’s exactly right.

Now we just have to tell our program to pick a random item from this new typing_prompts list.

The old line was sentence_to_type = random.choice(sentences). How would you change it to use our new list and a more general variable name, like prompt_to_type?

User

prompt_to_type = random.choice(typing_prompts)

AI

You’ve got it. That’s the last change we need to make.

With that, the game will now randomly pick either a single word or a full sentence for the user to type. The rest of the code works just as it did before.


Final Code

Here is the complete, final version of the game with all the improvements you added.

Python

import random
import time

# --- Setup ---
words = ["house", "something", "video", "chronic", "another"]
sentences = ["the quick brown fox jumped over the lazy dog", "Sphinx of black quartz, judge my vow"]

typing_prompts = words + sentences
prompt_to_type = random.choice(typing_prompts)


# --- Main Game Loop ---
print("--- Typing Game ---")
print("Type this:", prompt_to_type)

start_time = time.time()
user_input = input("> ")
end_time = time.time()


# --- Calculations & Results ---
duration_seconds = end_time - start_time

if duration_seconds > 0:
    duration_minutes = duration_seconds / 60
    number_of_words = len(user_input) / 5
    wpm = number_of_words / duration_minutes
else:
    wpm = 0

print("--- Results ---")

if prompt_to_type == user_input:
    print("Accuracy: Correct!")
else:
    print("Accuracy: Incorrect!")

print("Your speed:", round(wpm), "WPM")

You did an amazing job, not just building a program but also thinking of ways to improve it and then implementing those changes. That’s what programming is all about.

What are you curious about next? We could keep adding features to this game or start a brand new project.

User

does our final code contain the defining and calling of a function?

AI

That’s an excellent question that gets to the heart of how code is organized.

Your final code is very good at calling functions, but it doesn’t define any of its own.

Think of it like this:

  • Calling a function is like using a tool from a toolbox (e.g., using a pre-made hammer).
  • Defining a function is like building your own custom tool and putting it in the toolbox for later use.

Calling Functions (You do this a lot!) 🧰

Your code calls many pre-built functions to perform actions. This is a fundamental part of programming.

Here are all the functions you call in your script:

  • random.choice(): To pick a random item from your list.
  • print(): To display text on the screen.
  • time.time(): To get the current timestamp.
  • input(): To pause the program and get input from the user.
  • len(): To get the length of the user’s input string.
  • round(): To round the final WPM to a whole number.

Defining Functions (The next step!) πŸ› οΈ

Your code does not define any new, custom functions. Defining a function involves using the def keyword to create a reusable block of code with its own name.

For example, we could have defined a function to handle the WPM calculation like this:

Python

# This is a function DEFINITION
def calculate_wpm(duration, text_typed):
    # This code is inside the function
    if duration <= 0:
        return 0
    
    number_of_words = len(text_typed) / 5
    minutes = duration / 60
    wpm = number_of_words / minutes
    return wpm

# --- Later in the code ---
# This is a function CALL
final_wpm = calculate_wpm(duration_seconds, user_input)

Your current code is a procedural scriptβ€”it runs from top to bottom. As programs get more complex, programmers define functions to keep the code organized, avoid repetition, and make it easier to read.

User

is there a way to incorporate this defining function into our code?

AI

Yes, absolutely. Incorporating your own defined function is an excellent way to make your code more organized and readable.

The best candidate for a function in your script is the WPM calculation logic. It’s a self-contained task: it takes in the duration and the typed text, and it produces a single result (the WPM).

Let’s refactor the code to use a function.


The Benefits of Using a Function Here

  • Organization: It bundles all the calculation logic into one place, keeping your main code clean.
  • Readability: The main part of your code will read like plain English (e.g., wpm = calculate_wpm(...)), making it easier to understand at a glance.
  • Reusability: If your game became more complex, you could reuse this function elsewhere without copying and pasting the code.

How to Do It

We’ll take the calculation block and wrap it in a function definition using def.

1. Define the Function

We’ll create a function named calculate_wpm that takes two inputs (parameters): the time duration and the text the user typed. The code inside the function will be your existing calculation logic. At the end, it will use return to send the final answer back.

Python

# --- Function Definition ---
def calculate_wpm(duration, text_typed):
    """Calculates the words per minute."""
    if duration <= 0:
        return 0  # Use 'return' to send back an answer and exit the function
    
    number_of_words = len(text_typed) / 5
    minutes = duration / 60
    wpm = number_of_words / minutes
    return wpm # Send the final calculation back

2. Call the Function in Your Main Code

Now, the “Calculations & Results” section of your code becomes much simpler. You just need to call your new function and give it the data it needs.

Python

# --- Calculations & Results ---
duration_seconds = end_time - start_time

# We replaced the multi-line calculation with one clean function call
wpm = calculate_wpm(duration_seconds, user_input)

print("--- Results ---")
# ... the rest of the code stays the same

Notice how the if duration_seconds > 0: check is now handled inside the function, making the main logic even cleaner.


The Complete Refactored Code

Here is what your final code looks like with the custom function included. It does the exact same thing as before, but it’s better organized. βœ…

Python

import random import time # — Function Definition — def calculate_wpm(duration, text_typed): “””Calculates the words per minute.””” if duration <= 0: return 0 number_of_words = len(text_typed) / 5 minutes = duration / 60 wpm = number_of_words / minutes return wpm # — Setup — words = [“house”, “something”, “video”, “chronic”, “another”] sentences = [“the quick brown fox jumped over the lazy dog”, “Sphinx of black quartz, judge my vow”] typing_prompts = words + sentences # — Main Game Loop — prompt_to_type = random.choice(typing_prompts) print(“— Typing Game —“) print(“Type this:”, prompt_to_type) start_time = time.time() user_input = input(“> “) end_time = time.time() # — Calculations & Results — duration_seconds = end_time – start_time wpm = calculate_wpm(duration_seconds, user_input) # Calling our new function! print(“— Results —“) if prompt_to_type == user_input: print(“Accuracy: Correct!”) else: print(“Accuracy: Incorrect!”) print(“Your speed:”, round(wpm), “WPM”)

When conversing with this ai, I used the guiding learning tool and a strong starting question to help me learn and use these skills.

My final Code

import random
import time

# Function Defining
def calculate_wpm(duration, text_typed):
    """Calculates the words per minute."""
    if duration <= 0:
        return 0
    
    number_of_words = len(text_typed) / 5
    minutes = duration / 60
    wpm = number_of_words / minutes
    return wpm

# Code setup
words = ["house", "something", "video", "chronic", "another"]
sentences = ["the quick brown fox jumped over the lazy dog", "Sphinx of black quartz, judge my vow"]
typing_prompts = words + sentences

# Game Loop
prompt_to_type = random.choice(typing_prompts)
print("--- Typing Game ---")
print("Type this:", prompt_to_type)

start_time = time.time()
user_input = input("> ")
end_time = time.time()

# Calculating and result
duration_seconds = end_time - start_time
wpm = calculate_wpm(duration_seconds, user_input) # Calling our new function!

print("--- Results ---")

if prompt_to_type == user_input:
    print("Accuracy: Correct!")
else:
    print("Accuracy: Incorrect!")

print("Your speed:", round(wpm), "WPM")

My final code included many beginner basic python coding skills, such as module/imports, variable, data types, list operations, input output, time measurement, conditionals, defining functions, and some others.

Code explanation

Import :

Import random – Allows me to access random words and choices

Import time – Allows me to use start and stop / Timer

Setup : 

Words – A group of words to choose from (randomly)

Sentences – Sentences to choose from (randomly)

Typing_prompts – we can make a full list of random choices using the β€œ+” feature to add the lists.

Game Loop

prompt_to_type = random.choice(typing_prompts): The computer picks one random sentence/word from the full master list and stores it in the prompt_to_type variable.

print(…): The lines display the game title and the chosen prompt to the user.

start_time = time.time(): The program records a precise timestamp right before waiting for the user to type.

user_input = input(“> “): The program pauses and waits for the user to type something and press Enter. Whatever they type is stored in the user_input variable.

end_time = time.time(): The instant the user presses Enter, the program records a new timestamp.

Calculations / Timestamps

duration_seconds = end_time – start_time: It calculates how long the user took by subtracting the start time from the end time.

if duration_seconds > 0:: It checks to make sure time has actually passed to prevent a “division by zero” error. If it has, it performs all the WPM calculations. Otherwise, it just sets wpm to 0.

if prompt_to_type == user_input:: It compares the original prompt with what the user typed to check for accuracy and prints the appropriate message.

print(“Your speed:”, round(wpm), “WPM”): Finally, it displays the WPM score. It uses the round() function to make the number a clean integer before showing it to the user.

Defining Functions

[def]: This is the Python keyword that says, “I am now defining a new function.”

[calculate_wpm]: This is the name I will use to refer to later in my code.

( ): The parentheses hold the inputs the function needs to do its job.

duration, text_typed: These are the parameters, they are placeholders for the actual data I give the function when I call it.

:: The colon marks the end of the definition line and the beginning of the function’s code block.

This coding assignment has been a blast and I hope to further enhance my skills!

Comments

2 Responses to “Coding – Fusion”

  1. mcrompton Avatar
    mcrompton

    This is pretty good, Matthew. I feel like you have come at this with some background in Python. Your responses to the questions that AI gave you were often perfect from the start, although there are times when you were looking for more guidance. I think that it would have helped to at least have told it what the requirements of the assignment were. You’ve missed a key piece, and that is the defintion and calling of a function. Also, if you recall our conversation in class, the flowchart is a planning tool to organize the logic of your code, not an explanation of how you approached the assignment. Can you please redo the flowchart and edit the code to include the required function and resubmit?

    1. mcrompton Avatar
      mcrompton

      Thank you, Matthew.

Leave a Reply to mcrompton Cancel reply

Your email address will not be published. Required fields are marked *