简体   繁体   中英

Understanding functions

So I've been practicing with functions but it just occurred to me now:

When you type in float(3.14) , you are simply calling the float function that has already been defined by the almighty built in Python. It works similarly to user defined functions like this one:

def power (x):
    for i in range(x):
        x2=i**2
        print(x2)

power(4)

I mean float is also a data type so its probably not exactly the same, but is my logic sound?

float is a type. At the same time, it is callable like a function:

>>> type(float)
<class 'type'>
>>> callable(float)
True


>>> def power (x):
...     for i in range(x):
...         x2=i**2
...         print(x2)
...
>>> type(power)
<class 'function'>
>>> callable(power)
True

In python, types, classes, objects with __call__ methods beside functions, methods are callable.

You are correct that you're calling a float() function, yes.

On a different note:

The power function that you've defined probably doesn't behave like you want it to.

You're shadowing your x parameter in the function with your x variable in the for loop.

No matter what you input, you're getting the same result because your x is instantly overwritten.

def power (x):
    for x in range(6):
        x = x ** 2
        print(x)

>>> power(1)
0
1
4
9
16
25
>>> power(10)
0
1
4
9
16
25

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM