The Grumpy Lion
The Grumpy Lion

Reputation: 173

Python - How to create a user-defined function to convert an integer into a float-type number?

I need to create a user-defined function (def) that simply converts an integer into a float-type number. Here's the code I've been trying to do:

def conversion():
    num = int(input("Enter number: "))
    return num
    e = float(num)
result= conversion()
print("Result: " +str(e))

For example, if I entered 56 the expected result would be 56.0 but instead I got the error:name 'e' is not defined

Upvotes: 0

Views: 1422

Answers (2)

Austin
Austin

Reputation: 26039

Problems:

  • You return num before you use float, so the returned value is always an integer.

  • You print e outside function, but is defined in the local scope of the function.

Corrected code:

def conversion():
    num = int(input("Enter number: "))
    # return num
    e = float(num)
    return e

result = conversion()
print("Result: " + str(result))

Upvotes: 2

Bale
Bale

Reputation: 621

As the comments say, your problem is with indentation, here's what it should look like:

def conversion():
   num = int(input("Enter number: "))
   return num
e = float(num)
result= conversion()
print("Result: " +str(e))

Upvotes: 0

Related Questions