我已经定义了这个没有参数的函数
# Define the function shout
def shout():
"""Print a string with three exclamation marks"""
# Concatenate the strings: shout_word
shout_word = str('congratulations')+ str('!!!')
# Print shout_word
print(shout_word)
# Call shout
shout(hello)
调用函数时出错,可能是什么原因? 非常感谢您的协助
答案 0 :(得分:1)
# Define the function shout
def shout(word): # Function shout() takes argument word
print(str(word) + '!!!') # Converting to str in case word should be an int
word = 'congratulations'
shout(word) # Call function shout with variable word.
使用第二个n_exclamation mark参数来进一步解释函数和参数的工作原理:
# Define the function shout
def shout(word, n_exclamation=3): # Function shout() takes argument word and n_exclamation, here n_exclamation is set to 3 in case we do not pass it whne we call shout()
print(str(word) + ('!' * n_exclamation)) # Converting to str in case word should be an int
word = 'congratulations'
shout(word, 1) # Call function shout with variable word, print 1 exclamation marks (n_exclamation).
shout(word) # Call function shout with variable word, will print 3 exclamation marks since we didn't pass any argument to that variable, the function is declared to have a default of 3 when that happens.