summaryrefslogtreecommitdiffhomepage
path: root/python.html.markdown
diff options
context:
space:
mode:
Diffstat (limited to 'python.html.markdown')
-rw-r--r--python.html.markdown161
1 files changed, 125 insertions, 36 deletions
diff --git a/python.html.markdown b/python.html.markdown
index 63547bf6..675967f4 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -4,6 +4,7 @@ contributors:
- ["Louie Dinh", "http://ldinh.ca"]
- ["Amin Bandali", "http://aminbandali.com"]
- ["Andre Polykanine", "https://github.com/Oire"]
+ - ["evuez", "http://github.com/evuez"]
filename: learnpython.py
---
@@ -14,7 +15,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
@@ -46,12 +53,18 @@ to Python 2.x. For Python 3.x, take a look at the [Python 3 tutorial](http://lea
2.0 # This is a float
11.0 / 4.0 # => 2.75 ahhh...much better
-# Result of integer division truncated down both for positive and negative.
+# Result of integer division truncated down both for positive and negative.
5 // 3 # => 1
5.0 // 3.0 # => 1.0 # works on floats too
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
+# Note that we can also import division module(Section 6 Modules)
+# to carry out normal division with just one '/'.
+from __future__ import division
+11/4 # => 2.75 ...normal division
+11//4 # => 2 ...floored division
+
# Modulo operation
7 % 3 # => 1
@@ -141,12 +154,14 @@ bool("") # => False
## 2. Variables and Collections
####################################################
-# Python has a print statement, in all 2.x versions but removed from 3.
-print "I'm Python. Nice to meet you!"
-# Python also has a print function, available in versions 2.7 and 3...
-# but for 2.7 you need to add the import (uncommented):
-# from __future__ import print_function
-print("I'm also Python! ")
+# Python has a print statement
+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
@@ -157,6 +172,7 @@ some_var # => 5
some_other_var # Raises a name error
# if can be used as an expression
+# Equivalent of C's '?:' ternary operator
"yahoo!" if 3 > 2 else 2 # => "yahoo!"
# Lists store sequences
@@ -195,7 +211,7 @@ li[2:] # => [4, 3]
li[:3] # => [1, 2, 4]
# Select every second entry
li[::2] # =>[1, 4]
-# Revert the list
+# Reverse a copy of the list
li[::-1] # => [3, 4, 2, 1]
# Use any combination of these to make advanced slices
# li[start:end:step]
@@ -210,6 +226,17 @@ li + other_li # => [1, 2, 3, 4, 5, 6]
# Concatenate lists with "extend()"
li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
+# Remove first occurrence of a value
+li.remove(2) # li is now [1, 3, 4, 5, 6]
+li.remove(2) # Raises a ValueError as 2 is not in the list
+
+# Insert an element at a specific index
+li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again
+
+# Get the index of the first item found
+li.index(2) # => 3
+li.index(7) # Raises a ValueError as 7 is not in the list
+
# Check for existence in a list with "in"
1 in li # => True
@@ -301,6 +328,15 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# Do set difference with -
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+# Do set symmetric difference with ^
+{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
+
+# Check if set on the left is a superset of set on the right
+{1, 2} >= {1, 2, 3} # => False
+
+# Check if set on the left is a subset of set on the right
+{1, 2} <= {1, 2, 3} # => True
+
# Check for existence in a set with in
2 in filled_set # => True
10 in filled_set # => False
@@ -316,11 +352,11 @@ some_var = 5
# Here is an if statement. Indentation is significant in python!
# prints "some_var is smaller than 10"
if some_var > 10:
- print("some_var is totally bigger than 10.")
+ print "some_var is totally bigger than 10."
elif some_var < 10: # This elif clause is optional.
- print("some_var is smaller than 10.")
+ print "some_var is smaller than 10."
else: # This is optional too.
- print("some_var is indeed 10.")
+ print "some_var is indeed 10."
"""
@@ -331,8 +367,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
@@ -344,7 +380,19 @@ prints:
3
"""
for i in range(4):
- print(i)
+ print i
+
+"""
+"range(lower, upper)" returns a list of numbers
+from the lower number to the upper number
+prints:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print i
"""
While loops go until a condition is no longer met.
@@ -356,7 +404,7 @@ prints:
"""
x = 0
while x < 4:
- print(x)
+ print x
x += 1 # Shorthand for x = x + 1
# Handle exceptions with a try/except block
@@ -371,7 +419,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
@@ -379,7 +433,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
@@ -398,7 +452,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
@@ -408,8 +462,8 @@ keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
# You can do both at once, if you like
def all_the_args(*args, **kwargs):
- print(args)
- print(kwargs)
+ print args
+ print kwargs
"""
all_the_args(1, 2, a=3, b=4) prints:
(1, 2)
@@ -431,22 +485,22 @@ def pass_all_the_args(*args, **kwargs):
print varargs(*args)
print keyword_args(**kwargs)
-# Function Scope
+# Function Scope
x = 5
-def setX(num):
+def set_x(num):
# Local var x not the same as global variable x
x = num # => 43
print x # => 43
-
-def setGlobalX(num):
+
+def set_global_x(num):
global x
print x # => 5
x = num # global var x is now set to 6
print x # => 6
-setX(43)
-setGlobalX(6)
+set_x(43)
+set_global_x(6)
# Python has first class functions
def create_adder(x):
@@ -459,9 +513,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
@@ -487,9 +544,13 @@ class Human(object):
# Assign the argument to the instance's name attribute
self.name = name
+ # Initialize property
+ self.age = 0
+
+
# 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
@@ -502,13 +563,30 @@ class Human(object):
def grunt():
return "*grunt*"
+ # A property is just like a getter.
+ # It turns the method age() into an read-only attribute
+ # of the same name.
+ @property
+ def age(self):
+ return self._age
+
+ # This allows the property to be set
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+ # This allows the property to be deleted
+ @age.deleter
+ def age(self):
+ del self._age
+
# Instantiate a class
i = Human(name="Ian")
-print(i.say("hi")) # prints out "Ian: hi"
+print i.say("hi") # prints out "Ian: hi"
j = Human("Joel")
-print(j.say("hello")) # prints out "Joel: hello"
+print j.say("hello") # prints out "Joel: hello"
# Call our class method
i.get_species() # => "H. sapiens"
@@ -521,6 +599,16 @@ j.get_species() # => "H. neanderthalensis"
# Call the static method
Human.grunt() # => "*grunt*"
+# Update the property
+i.age = 42
+
+# Get the property
+i.age # => 42
+
+# Delete the property
+del i.age
+i.age # => raises an AttributeError
+
####################################################
## 6. Modules
@@ -528,12 +616,12 @@ Human.grunt() # => "*grunt*"
# You can import modules
import math
-print(math.sqrt(16)) # => 4
+print math.sqrt(16) # => 4
# You can get specific functions from a module
from math import ceil, floor
-print(ceil(3.7)) # => 4.0
-print(floor(3.7)) # => 3.0
+print ceil(3.7) # => 4.0
+print floor(3.7) # => 3.0
# You can import all functions from a module.
# Warning: this is not recommended
@@ -579,7 +667,7 @@ xrange_ = xrange(1, 900000000)
# will double all numbers until a result >=30 found
for i in double_numbers(xrange_):
- print(i)
+ print i
if i >= 30:
break
@@ -608,24 +696,25 @@ def say(say_please=False):
return msg, say_please
-print(say()) # Can you buy me a beer?
-print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
+print say() # Can you buy me a beer?
+print say(say_please=True) # Can you buy me a beer? Please! I am poor :(
```
## Ready For More?
### 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)
-