summaryrefslogtreecommitdiffhomepage
path: root/python.html.markdown
diff options
context:
space:
mode:
Diffstat (limited to 'python.html.markdown')
-rw-r--r--python.html.markdown40
1 files changed, 31 insertions, 9 deletions
diff --git a/python.html.markdown b/python.html.markdown
index ace3f794..b939ebbe 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -14,7 +14,13 @@ executable pseudocode.
Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service]
Note: This article applies to Python 2.7 specifically, but should be applicable
-to Python 2.x. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
+to Python 2.x. Python 2.7 is reachong end of life and will stop beeign maintained in 2020,
+it is though recommended to start learnign Python with Python 3.
+For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
+
+It is also possible to write Python code which is compatible with Python 2.7 and 3.x at the same time,
+using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports
+allow you to write Python 3 code that will run on Python 2, so check out the Python 3 tutorial.
```python
@@ -142,7 +148,13 @@ bool("") # => False
####################################################
# Python has a print statement
-print "I'm Python. Nice to meet you!"
+print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!
+
+# Simple way to get input data from console
+input_string_var = raw_input("Enter some data: ") # Returns the data as a string
+input_var = input("Enter some data: ") # Evaluates the data as python code
+# Warning: Caution is recommended for input() method usage
+# Note: In python 3, input() is deprecated and raw_input() is renamed to input()
# No need to declare variables before assigning to them.
some_var = 5 # Convention is to use lower_case_with_underscores
@@ -198,7 +210,7 @@ li[::-1] # => [3, 4, 2, 1]
# Remove arbitrary elements from a list with "del"
del li[2] # li is now [1, 2, 3]
-r
+
# You can add lists
li + other_li # => [1, 2, 3, 4, 5, 6]
# Note: values for li and for other_li are not modified.
@@ -327,8 +339,8 @@ prints:
mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
- # You can use % to interpolate formatted strings
- print "%s is a mammal" % animal
+ # You can use {0} to interpolate formatted strings. (See above.)
+ print "{0} is a mammal".format(animal)
"""
"range(number)" returns a list of numbers
@@ -379,7 +391,13 @@ except (TypeError, NameError):
pass # Multiple exceptions can be handled together, if required.
else: # Optional clause to the try/except block. Must follow all except blocks
print "All good!" # Runs only if the code in try raises no exceptions
+finally: # Execute under all circumstances
+ print "We can clean up resources here"
+# Instead of try/finally to cleanup resources you can use a with statement
+with open("myfile.txt") as f:
+ for line in f:
+ print line
####################################################
## 4. Functions
@@ -387,7 +405,7 @@ else: # Optional clause to the try/except block. Must follow all except blocks
# Use "def" to create new functions
def add(x, y):
- print "x is %s and y is %s" % (x, y)
+ print "x is {0} and y is {1}".format(x, y)
return x + y # Return values with a return statement
# Calling functions with parameters
@@ -406,7 +424,7 @@ varargs(1, 2, 3) # => (1, 2, 3)
# You can define functions that take a variable number of
-# keyword args, as well, which will be interpreted as a map if you do not use **
+# keyword args, as well, which will be interpreted as a dict if you do not use **
def keyword_args(**kwargs):
return kwargs
@@ -467,9 +485,12 @@ add_10(3) # => 13
# There are also anonymous functions
(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
# There are built-in higher order functions
map(add_10, [1, 2, 3]) # => [11, 12, 13]
+map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
+
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
# We can use list comprehensions for nice maps and filters
@@ -497,7 +518,7 @@ class Human(object):
# An instance method. All methods take "self" as the first argument
def say(self, msg):
- return "%s: %s" % (self.name, msg)
+ return "{0}: {1}".format(self.name, msg)
# A class method is shared among all instances
# They are called with the calling class as the first argument
@@ -624,16 +645,17 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :(
### Free Online
+* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
* [Dive Into Python](http://www.diveintopython.net/)
* [The Official Docs](http://docs.python.org/2.6/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
* [Python Module of the Week](http://pymotw.com/2/)
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
### Dead Tree
* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
-