Problem 1: Procedural Programming
Learn how to use an AI assistant to create a function using procedural programming techniques, enhancing our coding skills.
Quick refresher
In the world of programming, we come across various programming styles, each with its own way of organizing code. One of the most common and beginner-friendly styles is procedural programming.
In procedural programming, the focus is on creating sequences of steps, called procedures, to perform tasks. The program’s flow is largely linear—starting at the top and moving step by step, much like how we might follow instructions to bake a cake. We define variables to store data and then create procedures that manipulate or interact with that data to solve a problem. Let’s consider this simple example in which we use procedural programming to store numbers in two variables, add them, and then display their result.
# Procedure 1: Saving a number in a variablenum1 = 2# Procedure 2: Saving another number in a variablenum2 = 7# Procedure 3: Add the two numbers together and save answer in a variablesummation = num1 + num2# Procedure 4: Printing the result of summationprint(summation)
Procedural programming is a great starting point for learning to code because it teaches core concepts such as variables, loops, and conditionals, which are all essential building blocks for coding.
However, when working on larger projects, relying solely on procedural programming can lead to a code that is difficult to manage and scale.
This is where the concept of functions comes into play. We can better organize the program by breaking the code into smaller, reusable chunks called functions. These functions can then be stitched together in a specific sequence, much like how steps are followed in procedural programming. Here’s an example:
# Function to calculate the area of a rectangledef calculate_rectangle_area(length, width):return length * width# Function to calculate the area of a circledef calculate_circle_area(radius):pi = 3.14159return pi * (radius ** 2)# Main program (sequence of steps)def main():# Define variables containing the dimensions of the rectanglelength = 5width = 3# Call the function to calcualte the area of trianglerectangle_area = calculate_rectangle_area(length, width)# Define a variable for the area of circleradius = 2.5# Call the function to calculate the area of the circlecircle_area = calculate_circle_area(radius)# Print resultsprint(f"The area of the rectangle is: {rectangle_area}")print(f"The area of the circle is: {circle_area}")# Call the main function to run the programmain()
Note: In each lesson moving forward, we’ll start with guided steps to demonstrate how to make the most of AI as your coding assistant, based on the type of coding challenge, just like an effective problem-solver would. After that, we’ll give you a coding exercise (it could be the same or different one) to solve on your own.
Guided steps
Now let’s look at an example of how to use an AI assistant to help you generate code that require procedural and functional programming and guide you through the effective prompting techniques!
Before we begin, the following are the ways in which our AI coding assistant can act as our thought partner:
Discuss what the modular breakdown of the program should look like, considering the requirements.
Discuss what each function should do, and what should be its inputs and outputs.
Get code for the
main()
function and any other supporting function(s) (if needed).Get help debugging the code.
Problem statement
Create a simple command line factorial calculator using Python.
To help you get the most out of an AI coding assistant while at the same time staying in control, we’ll walk you through a sample solution to solve this problem and brainstorm the solution together with AI. Toward the end of the lesson, you’ll solve a different problem independently.
It is vital to know that AI is a tool to assist you, but you should guide the process, make final choices, and ultimately complete the solution yourself.
So let’s begin!
Conversation with the AI assistant
Following is the initial part of our conversation with our assistant.
I want you to act as my coding assistant and brainstorming partner. You help me brainstorm ideas, suggest best practices, and guide my thought process based on project needs. However, I remain fully in control of my project—you must not provide any code without first getting my approval. I need you to explain each suggestion clearly and concisely so that I fully understand each solution element before proceeding. Your suggestions should be framed as options or ideas rather than final solutions, and they should be aimed at helping me improve my coding skills and problem-solving abilities. Remember, every line of code needs to go through me before it’s written.
I’m ready to help! What project would you like to start with, or what ideas are you thinking about?
Great! We have to make a simple command line factorial calculator using Python. What options are there for us to explore?
A factorial calculator is a great choice for exploring basic programming concepts. Here are some options to consider for building this tool, each focusing on different aspects of Python and user interaction:
1. Basic Recursive Function Approach
Idea: Implement a recursive function to calculate the factorial. In this approach, the function calls itself with smaller values until it reaches 1, which serves as the base case.
Advantages: This approach introduces recursion, which is useful in other areas of programming, and highlights the importance of base cases.
Considerations: For large numbers, recursion can lead to a stack overflow error. Python has a recursion limit, so this may not work well for very large inputs. We can explore setting a safe limit if needed.
2. Iterative Function Approach
Idea: Use a loop (either for or while) to calculate the factorial. This approach multiplies numbers in sequence up to the specified number.
Advantages: Iteration is generally faster and more memory-efficient than recursion for factorials, especially with large numbers, and it avoids stack overflow risks.
Considerations: This is a great way to understand iterative loops in Python, and it’s likely the most efficient solution for basic use.
3. Using Python’s Built-in math.factorial()
Idea: Leverage the math.factorial() function from Python’s standard library.
Advantages: This approach is the simplest and most efficient, as it uses Python’s optimized internal code for factorials. It’s also less error-prone.
*Considerations: It’s a great way to learn about Python libraries, but it skips implementing the logic yourself, which can be a valuable learning experience. Each approach has its strengths and trade-offs, depending on how deep you want to dive.
Let me know which ones resonate with you or if you’d like more details on any specific option!
Let’s go with the iterative function approach. We’ll follow the following structure:
- Define the calculate_factorial function.
- Call the function in main and test it.
Let’s proceed with the first step.
Step 1: Define the calculate_factorial Function
In this step, we’ll create a function named calculate_factorial that takes a positive integer n as an argument and returns the factorial of n. Here’s the plan:
Initialize a Variable result:
Start with result set to 1. This will hold the cumulative product as we multiply each integer from 1 to n.
Iterate Over the Range from 1 to n:
Use a for loop to go through each number from 1 up to and including n. Multiply result by each number in this range, updating result each time.
Return the Final Result:
After the loop finishes, result will contain the factorial of n, so we’ll return it from the function.
Code Outline for calculate_factorial
def calculate_factorial(n): result = 1 for i in range(1, n + 1): result *= i # Multiply result by the current number return result
We have the full functionality of calculating the factorial. Would you like to test this out or add any modifications before we proceed?
I’d like to test it now.
Step 2: Call the calculate_factorial Function:
To test the function, call calculate_factorial inside the main() function.
After the factorial is calculated, print the result in a user-friendly format.
Example Code for Full Functionality
def calculate_factorial(n): result = 1 for i in range(1, n + 1): result *= i # Multiply result by the current number return result def main(): factorial = calculate_factorial(n) # Calculate the factorial print(f"The factorial of {n} is {factorial}.") # Print the result main() # Call the main function
Explanation:
- calculate_factorial(n): Takes the input and computes the factorial.
- print(): Displays the calculated factorial.
Let me know how the test goes or if you’d like me to help with any modifications or fixes!
Run your code here
We’ve included the AI-generated solution in the widget below. You can run it and see if it’s working properly.
# Step 1: Define the calculate_factorial function def calculate_factorial(n): result = 1 for i in range(1, n + 1): result *= i # Multiply result by the current number return result # Step 2: Main function to combine everything def main(): # Calculate the factorial using the iterative function result = calculate_factorial(n) # Print the result print(f"The factorial of {n} is {result}") # Run the program if __name__ == "__main__": main()
Coding exercise
Now that we’ve seen the guided steps to generate code for a coding problem, it’s time you use an AI assistant to generate code yourself for a different problem statement.
Problem statement
Create a currency converter that converts amounts between two currencies (USD to EUR and EUR to USD) using a predefined exchange rate.
Before jumping straight to ChatGPT, it’s best to brainstorm on your own first. To develop strong problem-solving skills and avoid over-reliance, always ensure you fully understand the problem and try to come up with a solution or approach independently before seeking help.
Work with the AI assistant
Work with your AI assistant (given below) and solve this coding problem similarly.
Tip: Get code from the assistant for each function (given there is more than one function) and run it in the code widget (the Prompt AI widget below) to test if it is error-free. You might be tempted to generate the entire code from your AI assistant in one go but that’s a poor approach and will result in no learning of your own. If there happens to be an error, this way you’ll be able to figure out and debug it along the way. You have 15 attempts to interact with the AI assistant. Use it wisely to get your program up and running!
Run your code here
You can add and test the code as you work through this challenge in the widget below.
# Add and test your code here.
We’ve added one of the possible solutions along with the prompts we used to solve this challenge using the assistant below: