diff options
author | Adam <adam@adambard.com> | 2013-06-28 08:58:14 -0700 |
---|---|---|
committer | Adam <adam@adambard.com> | 2013-06-28 08:58:14 -0700 |
commit | b34908e050507ac4e582f8cdc5b314027274c3e4 (patch) | |
tree | 6502ed55857674823ec7e09b887af8d2725bd8ee | |
parent | 6634622d54c5a26dca9d1963974ec735261c13cd (diff) | |
parent | c0fcff3cabf3fc0e5a4667deb8f41e30e89093f2 (diff) |
Merge branch 'master' of https://github.com/adambard/learnxinyminutes-docs
-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): |