谷歌Python练习

-1 投票
5 回答
2162 浏览
提问于 2025-04-17 09:29

我在YouTube上看教学视频,并开始在http://code.google.com/edu/languages/google-python-class上做一些练习,但我对strings1.py文件中的一个问题感到困惑。
我不太明白的是,函数中的“s”在both_ends(s):里到底是干嘛的?

# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return instead the empty string.

def both_ends(s):
  # +++your code here+++
  # LAB(begin solution)
  if len(s) < 2:
    return ''
  first2 = s[0:2]
  last2 = s[-2:]
  return first2 + last2

在strings1.py的底部有一些函数:

def main()

    print 'both_ends'
    test(both_ends('spring'), 'spng')

if __name__ == '__main__':
  main()

那么程序是怎么知道把“spring”替换成(s)的呢?还是说它并不是这样做的?如果需要的话,我可以把整个文件发上来,只有140行。

5 个回答

0

当你调用一个函数时,你传给这个函数的值会被分配给函数头部对应的参数。简单来说,就是你在使用函数时,给它的输入会和函数定义里的参数一一对应起来。下面是代码示例:

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.
0

def both_ends(s) 这个函数里,s 是用来接收输入字符串的一个参数。我们通过 len(s) < 2 来检查这个字符串的长度是否小于2,也就是说,如果字符串太短,就不需要继续处理了。我们还可以通过 s[0:2]s[-2:] 来访问字符串中的不同字符,前者是获取字符串的前两个字符,后者是获取字符串的最后两个字符。

1

'spring' 是一个字面上的字符串,它作为参数传递给了名为 both_ends() 的函数,而 's' 是这个函数的正式参数。当我们调用这个函数时,实际参数会替换掉正式参数。

'test()' 函数的存在只是为了确认这个函数的表现是否符合预期。

撰写回答