Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
70 views
in Artificial Intelligence (AI) by (114k points)
Can you provide a code example of using ChatGPT to write a Python function for calculating the factorial of a number?

Please log in or register to answer this question.

1 Answer

0 votes
by (114k points)

Sure! Here's how you can interact with ChatGPT to generate the Python code for the factorial function:

# Import the OpenAI GPT-3 API library
import openai

# Set up your API key
api_key = "YOUR_OPENAI_API_KEY"

# Function to generate code using ChatGPT
def generate_code(prompt):
    # Initialize the OpenAI GPT-3 API client
    openai.api_key = api_key

    # Request code generation from ChatGPT
    response = openai.Completion.create(
        engine="text-davinci-002",  # You can choose a different engine based on your plan and requirements
        prompt=prompt,
        max_tokens=150,  # Adjust the token limit based on the complexity of the code
        temperature=0.7,  # Controls the randomness of the output. Lower values make it more focused, higher values make it more creative.
        n=1,  # Specifies the number of responses to generate
        stop=None,  # You can add custom stop sequences to control the response
    )

    # Extract the code from the API response
    generated_code = response.choices[0].text.strip()

    return generated_code

# Prompt for the factorial function
prompt = "Write a Python function to calculate the factorial of a number."

# Generate the code
generated_code = generate_code(prompt)

# Print the generated code
print(generated_code)
 

Remember to replace "YOUR_OPENAI_API_KEY" with your actual API key. The generated code may vary based on the prompt, model configuration, and temperature settings.

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...