diff options
author | Liteye <yelite958@gmail.com> | 2013-06-28 22:59:25 +0800 |
---|---|---|
committer | Liteye <yelite958@gmail.com> | 2013-06-28 22:59:25 +0800 |
commit | 9e17e878854531c75205147f30842850a75a5a20 (patch) | |
tree | de378ff9318c6a922766af9887f17585e7c1d784 /python.html.markdown | |
parent | 9b217bc769a4184fb14dfc58387a80e933c0859b (diff) |
add conditional expressions, get and setdefault for dictionary and a little tip about fuction calling.
Signed-off-by: Liteye <yelite958@gmail.com>
Diffstat (limited to 'python.html.markdown')
-rw-r--r-- | python.html.markdown | 21 |
1 files changed, 21 insertions, 0 deletions
diff --git a/python.html.markdown b/python.html.markdown index 300a5519..982333ca 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -99,6 +99,10 @@ try: except NameError: print "Raises a name error" +# Conditional Expressions can be used when assigning +some_var = a if a > b else b +# If a is greater than b, then a is assigned to some_var. +# Otherwise b is assigned to some_var. # Lists store sequences li = [] @@ -192,6 +196,17 @@ filled_dict.values() #=> [3, 2, 1] "one" in filled_dict #=> True 1 in filled_dict #=> False +# Trying to look up a non-existing key will raise a KeyError +filled_dict["four"] #=> KeyError + +# Use get method to avoid the KeyError +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# Setdefault method is a safe way to add new key-value pair into dictionary +filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5 + # Sets store ... well sets empty_set = set() @@ -311,6 +326,12 @@ all_the_args(1, 2, a=3, b=4) prints: {"a": 3, "b": 4} """ +# You can also use * and ** when calling a function +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +foo(*args) # equivalent to foo(1, 2, 3, 4) +foo(**kwargs) # equivalent to foo(a=3, b=4) +foo(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) # Python has first class functions def create_adder(x): |