How does passing input as an argument work?

时间:2018-01-07 00:20:13

标签: python python-3.x syntax

I've been using variables to pass as arguements this entire time, but I came across a solution that uses input and I'm having a hard time wrapping my head around how it works.

def reverse(input=''):
    return input[::-1]

What is the point of using input when you could do this?

def reverse(string):
    return string[::-1]

They both work exactly the same.
I thought using input would let you enter any string you want but it doesn't.
I got this from Excercism.

2 个答案:

答案 0 :(得分:2)

参数名称在这里无关紧要。实际上,第一个函数参数“遮蔽”input()函数。

  

我认为使用输入会让你输入任何你想要的字符串

被称为函数 时,确实已经定义了不是接受用户输入的函数的input变量。

这里的真正区别是参数

的默认值

你混淆了这个

def reverse(string):
    return string[::-1]

print(reverse(input())

有了这个

def reverse(input=''):
    return input[::-1]

print(reverse())  
print(reverse(input=input()) 

答案 1 :(得分:1)

reverse的这两个定义之间的唯一区别是第一个给出了参数的默认值。参数的名称无关紧要。

使用第一个定义

reverse()
# => ''

调用没有参数的第二个定义会导致错误。