![](/img/trans.png)
[英]Pythonic way to write REST wrapper function that takes optional arguments
[英]write a function that takes 2 string arguments
我是一個初學者,所以如果你被它的簡單冒犯了,請跳過這個。
我不知道如何編寫一個 function ,它需要兩個 arguments (名稱和課程)並打印:歡迎“名稱”到“課程”訓練營。
def greeting('name', 'course'):
print (welcome,'name', to, the, 'course')
我希望能夠打印歡迎 Stacie 參加 python 訓練營!
請嘗試以下類似的方法。
def greeting(name, course):
print ('welcome' + name + 'to' + 'the' + course)
greeting('Stacie', 'python')
如果您仍然收到任何錯誤,請分享錯誤截圖。
def greeting(name, course):
print (f"Welcome {name} to the {course}")
greeting("Jhon", "Python for Beginners")
# > Welcome Jhon to the Python for Beginners
function 有兩個變量,變量不是字符串,所以不會有引號。 在 print 語句中, f"<text>"
在這種情況下用於在{}
的幫助下打印字符串中的變量。 因此,當您輸入字符串{name}
時,它將從變量本身中獲取名稱。
您聲明的 function arguments 需要是變量,而不是實際值。
def greeting(name, course):
print ('welcome', name, 'to the', course)
注意你的引用是如何完全錯誤的。 人類可讀文本周圍的單引號 go 和周圍沒有引號的內容必須是有效的 Python 符號或表達式。
如果你想提供一個默認值,你可以這樣做。
def greeting(name='John', course='Python 101 course'):
print ('welcome', name, 'to the', course)
調用greeting()
將產生
welcome John to the Python 101 course
當然也可以用 arguments 來調用它
greeting('Slartibartfast', 'Pan Galactic Gargle Blaster course')
將使用您作為 arguments 傳遞的值填充變量:
welcome Slartibartfast to the Pan Galactic Gargle Blaster course
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.