Python Python Basics Functions and Looping Create a Function

Ali Zalzale
Ali Zalzale
901 Points

i can't do this help
def square(number):
    Return (square)*2
number = (input("choose a number"  ))
square = (number)**2
print (square)

1 Answer

Owen Bell
Owen Bell
7,722 Points

input returns a string based on the user input. You can't apply a power raising operation to a string, so we first need to convert the data type to an integer value using the int() function. The example below works for when the user enters an integer: you could build it out further to catch floating points for int conversion by using float() before, or within int().

The function itself is currently multiplying its parameter number by 2 instead of squaring it. As you've done outside the function body, just add one more * to the expression in the function body.

Then, you're not actually calling the function - you're just hard coding what the function should do if it were to be called. Call the function, passing in number as an argument, and save this to a new variable. Instead of square, I called it number_squared below just to avoid confusion between global variable square and function square().

All that sums up to:

def square(num):
  return num ** 2

number = int(input("Choose a number:  "))
number_squared = square(number)