summaryrefslogtreecommitdiffhomepage
path: root/python3.html.markdown
diff options
context:
space:
mode:
Diffstat (limited to 'python3.html.markdown')
-rw-r--r--python3.html.markdown34
1 files changed, 32 insertions, 2 deletions
diff --git a/python3.html.markdown b/python3.html.markdown
index 778076f8..bc0c05bd 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,9 +38,16 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria
# Except division which returns floats by default
35 / 5 # => 7.0
+# Truncation or Integer division
+5 // 3 # => 1
+5.0 // 3.0 # => 1.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
@@ -90,6 +98,10 @@ not False # => True
# 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 +296,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))
"""
@@ -406,6 +418,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):
@@ -445,7 +475,7 @@ class Human(object):
# 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