1. 程式人生 > >Python學習19:函數和變量 Function and variables

Python學習19:函數和變量 Function and variables

Python 函數

定義一個簡單的函數,調用函數輸出不同的內容

# -*- coding: utf-8 -*-
# 因為有中文註釋,為了防止腳本在運行的時候提示編碼錯誤,在腳本中需要加入上面一行代碼。
# 定義一個函數,使用格式化字符串輸出函數中參數的值
def cheese_and_crackers(cheese_count, boxes_of_crackers):
    print "You have %d cheeses!" % cheese_count
    print "You have %d boxes of crackers!" % boxes_of_crackers
    print "Man that‘s enough for a party!"
    print "Get a blanket.\n"

# 直接在函數中引用數值    
print "We can just give the function numbers directly:"
cheese_and_crackers(20, 30)

# 將兩個變量賦值,然後使用函數打印出兩個變量
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50

cheese_and_crackers(amount_of_cheese, amount_of_crackers)

# 使用函數直接計算數值的和
print "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)

# 使用函數計算變量和數值的和並打印出來,在調用函數的時候引用了上面的變量
print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)

Python學習19:函數和變量 Function and variables