谷歌python练习
我正在youtube上观看教学视频,并开始在上做一些练习,但我对string1.py文件中的以下问题感到困惑。 我似乎不明白的是,两端的“s”是什么:在做什么谷歌python练习,python,Python,我正在youtube上观看教学视频,并开始在上做一些练习,但我对string1.py文件中的以下问题感到困惑。 我似乎不明白的是,两端的“s”是什么:在做什么 那么,程序如何知道用“spring”来代替(s)呢?或者它不是这样做的?如果需要,我可以发布整个文件。只有140行。调用函数时,为函数指定的值将分配给函数标题中的相应参数。代码: def my_func(a): #function header; first argument is called a. #
那么,程序如何知道用“spring”来代替(s)呢?或者它不是这样做的?如果需要,我可以发布整个文件。只有140行。调用函数时,为函数指定的值将分配给函数标题中的相应参数。代码:
def my_func(a): #function header; first argument is called a.
#a is not a string, but a variable.
print a #do something with the argument
my_func(20) #calling my_func with a value of 20. 20 is assigned to a in the
#body of the function.
s
是一个我们假定包含字符串的变量。我们将“spring”作为参数传入。s
indef两端。
是输入字符串的参数。通过调用len(s)<2
检查此字符串的长度,并通过s[0:2]
和s[-2:]
按位置访问字符串中的各种字符,有关详细信息,请参阅。另外,上的教程也很不错-我主要是从中学习的。'spring'是作为参数传递到函数both_ends()的文本字符串,而's'是函数的形式参数。调用函数时,将使用实际参数替换形式参数。
“test()”函数只是用来确认函数的行为是否符合预期。
s
是函数的参数,但您可以在函数中插入真正的字符串,如hello
或world
,而不仅仅是字母s
。把它想象成一个数学函数:你有f(x)=x+5
。当你插入一个数字时,比如说2
,你会得到f(2)=2+5
。这正是两端函数所发生的情况。为了简化,下面是一些代码:
def f(x):
return x + 5
f(2)
在代码中插入函数的方式与在原始函数中插入字符串的方式相同。此测试函数可能是答案,但我仍然不明白它是如何工作的。
#提供了main()中使用的简单测试()函数,用于打印每个函数返回的内容与应该返回的内容。def测试(获取,预期):如果获取==预期:前缀='OK'其他:前缀='X'打印“%s获取:%s预期:%s%”(前缀,repr(获取),repr(预期))
def my_func(a): #function header; first argument is called a.
#a is not a string, but a variable.
print a #do something with the argument
my_func(20) #calling my_func with a value of 20. 20 is assigned to a in the
#body of the function.
def f(x):
return x + 5
f(2)