python函数适合初学者

时间:2014-06-06 02:37:14

标签: python function

我对python有些新意 - 我至少认为我对语法有了深刻的理解,但似乎无法弄清楚为什么这个函数不起作用。

我想写一个函数来大写字符串的字母。

string = 'Bryan'

def caps(word):
    word.upper()

caps(string)

我在这里不理解什么?对我来说似乎很基本,但无法弄清楚。任何帮助将不胜感激!

5 个答案:

答案 0 :(得分:6)

需要明确指定return

替换

word.upper()

return word.upper()

如果未指定return语句,则默认返回None,因此结果。

string = 'Bryan'

def caps(word):
    return word.upper()

returning_value = caps(string) #Note that you need to catch the returning the value. 
print returning_value

答案 1 :(得分:3)

你需要做两件事:

  1. 因为str.upper返回调用该方法的字符串的大写副本,所以您需要从函数word.upper()返回caps并且然后

  2. 将变量string重新分配给该返回值。

  3. 以下是您的脚本的外观:

    string = 'Bryan'
    
    def caps(word):
        return word.upper()
    
    string = caps(string)
    
    print string  # Print the new uppercased string
    

    演示:

    >>> string = 'Bryan'
    >>> def caps(word):
    ...     return word.upper()
    ...
    >>> string = caps(string)
    >>> print string
    BRYAN
    >>>
    

答案 2 :(得分:1)

string = 'Bryan'

def caps(word):
    word.upper()

caps(string)

我认为你错过了一个打印命令。

def caps(word):
        print word.upper()

如果要在变量中返回值,则必须返回函数中的值并将其赋值给变量。

def caps(word):
        return word.upper()

string = caps(string)

答案 3 :(得分:1)

你必须记住问自己,我希望这个功能做什么? 在许多情况下,您可能希望它为您提供结果。例如,返回

string = 'Bryan'

def caps(word):
    return word.upper()

newstring = caps(string)
print newstring

在某些情况下,您可能只希望函数执行您要执行的操作。

string = 'Bryan'

def pcaps(word):
    print word.upper()

pcaps(string)

答案 4 :(得分:0)

这也可以。您可以将word.upper()指定给变量,并将其称为单词。

def caps(word):

 word = word.upper()

 return word