Python Python Basics Functions and Looping Create a Function

Felix Belga
Felix Belga
4,267 Points

creating a square function in python


It's asking for me to create a function that squares value and returns it.
import math

def square(number):
    number = value*value
    return number
value = input("what value do you want?")

print("The answer is number")

1 Answer

Dane Parchment
Dane Parchment
9,749 Points

You need to review how functions and their parameters work in Python, as it stands now you aren't using them properly, which is why the code is failing. However, you are on the right track for solving the problem so don't get discouraged.

In an effort to help you solve this on your own I will first try to give some advice, at the end you will find the solution if you still can't figure it out on your own.

  1. Try to remember the point of a parameter in a function. Parameters are the data that you are passing into the function for it to use. Look at your parameter for the function, are you using it properly? Remember, the parameter should be the number that you are going to square.

  2. Remember variable scope currently you are using a variable that hasn't been defined yet in the function, so that isn't going to work for you. Also, ask yourself why you are even using those variables if you pass the data into the function as a parameter.

  3. Why create the extra variable in the function, all you really need to do is return the value of the parameter squared right?

  4. Why are you printing data, and asking for input? The challenge isn't asking you to do that. In general, you shouldn't be doing extra things that the challenge doesn't call for. This is because even if you get the right solution, it may trip up the assertion tests, and cause the challenge to fail. Also, it is good practice for the real world, because you wouldn't do extra things that you weren't told to do in work.

Try using the data above to fix your solution. If you still need help, however, here is the solution:

import math

def square(number):
    return number * number

Note that if you needed to read the solution I provided, I advise you to go back and re-watch previous videos in order to reinforce your learning. Because you aren't remembering the necessary concepts.