summaryrefslogtreecommitdiffhomepage
path: root/python3.html.markdown
diff options
context:
space:
mode:
Diffstat (limited to 'python3.html.markdown')
-rw-r--r--python3.html.markdown69
1 files changed, 54 insertions, 15 deletions
diff --git a/python3.html.markdown b/python3.html.markdown
index 778076f8..f6babaff 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -2,6 +2,7 @@
language: python3
contributors:
- ["Louie Dinh", "http://pythonpracticeprojects.com"]
+ - ["Steven Basart", "http://github.com/xksteven"]
filename: learnpython3.py
---
@@ -37,13 +38,21 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria
# Except division which returns floats by default
35 / 5 # => 7.0
+# 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
+
# When you use a float, results are floats
3 * 2.0 # => 6.0
+# Modulo operation
+7 % 3 # => 1
+
# Enforce precedence with parentheses
(1 + 3) * 2 # => 8
-
# Boolean values are primitives
True
False
@@ -52,7 +61,6 @@ False
not True # => False
not False # => True
-
# Equality is ==
1 == 1 # => True
2 == 1 # => False
@@ -71,7 +79,6 @@ not False # => True
1 < 2 < 3 # => True
2 < 3 < 2 # => False
-
# Strings are created with " or '
"This is a string."
'This is also a string.'
@@ -86,10 +93,16 @@ not False # => True
"{} can be {}".format("strings", "interpolated")
# You can repeat the formatting arguments to save some typing.
-"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") #=> "Jack be nimble, Jack be quick, Jack jump over the candle stick"
+"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
+#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick"
+
# You can use keywords if you don't want to count.
"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna"
+# If your Python 3 code also needs to run on Python 2.5 and below, you can also
+# still use the old style of formatting:
+"%s can be %s the %s way" % ("strings", "interpolated", "old")
+
# None is an object
None # => None
@@ -284,7 +297,7 @@ prints:
mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
- # You can use % to interpolate formatted strings
+ # You can use format() to interpolate formatted strings
print("{} is a mammal".format(animal))
"""
@@ -318,9 +331,12 @@ try:
raise IndexError("This is an index error")
except IndexError as e:
pass # Pass is just a no-op. Usually you would do recovery here.
+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
-
-# Python's offers a fundamental abstraction called the Iterable.
+# Python offers a fundamental abstraction called the Iterable.
# An iterable is an object that can be treated as a sequence.
# The object returned the range function, is an iterable.
@@ -328,7 +344,7 @@ filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
print(our_iterable) #=> range(1,10). This is an object that implements our Iterable interface
-i We can loop over it.
+# We can loop over it.
for i in our_iterable:
print(i) # Prints one, two, three
@@ -406,6 +422,24 @@ all_the_args(**kwargs) # equivalent to foo(a=3, b=4)
all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
+# Function Scope
+x = 5
+
+def setX(num):
+ # Local var x not the same as global variable x
+ x = num # => 43
+ print (x) # => 43
+
+def setGlobalX(num):
+ global x
+ print (x) # => 5
+ x = num # global var x is now set to 6
+ print (x) # => 6
+
+setX(43)
+setGlobalX(6)
+
+
# Python has first class functions
def create_adder(x):
def adder(y):
@@ -438,14 +472,17 @@ class Human(object):
# A class attribute. It is shared by all instances of this class
species = "H. sapiens"
- # Basic initializer
+ # Basic initializer, this is called when this class is instantiated.
+ # Note that the double leading and trailing underscores denote objects
+ # or attributes that are used by python but that live in user-controlled
+ # namespaces. You should not invent such names on your own.
def __init__(self, name):
# Assign the argument to the instance's name attribute
self.name = name
# An instance method. All methods take "self" as the first argument
def say(self, msg):
- return "{name}: {message}" % (name=self.name, message=msg)
+ return "{name}: {message}".format(name=self.name, message=msg)
# A class method is shared among all instances
# They are called with the calling class as the first argument
@@ -524,9 +561,11 @@ def double_numbers(iterable):
# double_numbers.
# Note range is a generator too. Creating a list 1-900000000 would take lot of
# time to be made
-_range = range(1, 900000000)
+# We use a trailing underscore in variable names when we want to use a name that
+# would normally collide with a python keyword
+range_ = range(1, 900000000)
# will double all numbers until a result >=30 found
-for i in double_numbers(_range):
+for i in double_numbers(range_):
print(i)
if i >= 30:
break
@@ -539,10 +578,10 @@ for i in double_numbers(_range):
from functools import wraps
-def beg(_say):
- @wraps(_say)
+def beg(target_function):
+ @wraps(target_function)
def wrapper(*args, **kwargs):
- msg, say_please = _say(*args, **kwargs)
+ msg, say_please = target_function(*args, **kwargs)
if say_please:
return "{} {}".format(msg, "Please! I am poor :(")
return msg