Learn Python in 10 Minutes



Comments



Description

Tutorial - Learn Python in 10 minutesNOTE: If you would like some Python development done, my company, Stochastic Technologies, is available for consulting. Also, this tutorial is available as a short ebook. Preliminary fluff So, you want to learn the Python programming language but can't find a concise and yet full-featured tutorial. This tutorial will attempt to teach you Python in 10 minutes. It's probably not so much a tutorial as it is a cross between a tutorial and a cheatsheet, so it will just show you some basic concepts to start you off. Obviously, if you want to really learn a language you need to program in it for a while. I will assume that you are already familiar with programming and will, therefore, skip most of the nonlanguage-specific stuff. The important keywords will be highlighted so you can easily spot them. Also, pay attention because, due to the terseness of this tutorial, some things will be introduced directly in code and only briefly commented on. Properties Python is strongly typed (i.e. types are enforced), dynamically, implicitly typed (i.e. you don't have to declare variables), case sensitive (i.e. var and VAR are two different variables) and object-oriented (i.e. everything is an object). Getting help Help in Python is always available right in the interpreter. If you want to know how an object works, all you have to do is call help(<object>)! Also useful are dir(), which shows you all the object's methods, and <object>.__doc__, which shows you its documentation string: ? 1 >>> help(5) 2 Help on int object: 3 (etc etc) 4 5 >>> dir(5) 6 ['__abs__', '__add__', ...] 7 8 >>> abs.__doc__ 9 'abs(number) -> number 10 11 Return the absolute value of the argument.' Syntax Python has no mandatory statement termination characters and blocks are specified by indentation. Indent to begin a block, dedent to end one. Statements that expect an indentation level end in a colon (:). Comments start with the pound (#) sign and are single-line, multi-line strings are used for multi-line Values are assigned (in fact.14] mylist[0] = "List item 1 again" mylist[-1] = 3. ("a". hash tables) and tuples are immutable one-dimensional arrays (Python "arrays" can be of any type. Leaving the start index empty assumes the first item.14} mydict["pi"] = 3. 2: 3. 2. 2. mystring = mystring. 14 # This swaps the variables in one line(!).k. ["another". strings included.15 mytuple = (1." 12 >>> print mystring 13 Hello world. 3) myfunction = len print myfunction(mylist) You can access array ranges using a colon (:). 3. tuples and dictionaries. and equality testing is done using two _equals_ signs ("=="). For example: ? 1 >>> myvar = 3 2 >>> myvar += 2 3 >>> myvar 4 5 5 >>> myvar -= 1 6 >>> myvar 7 4 8 """This is a multiline comment. etc in lists/dictionaries/tuples).14 mydict = {"Key 1": "Value 1". Sets are available in the sets library (but are built-in in Python 2. The usage is as follows: ? 1 >>> 2 >>> 3 >>> 4 >>> 5 >>> 6 >>> 7 >>> 8 >>> 9 >>> 10 3 sample = [1. Negative numbers count from the end towards the beginning. leaving the end index assumes the last item. dictionaries are associative arrays (a. 9 The following lines concatenate the two strings. -1 is the last item. Lists are like one-dimensional arrays (but you can also have lists of other lists). 18 >>> myvar. strings.comments. integers. Variables can point to functions. so you can mix e. The index of the first item in all array types is 0.""" 10 >>> mystring = "Hello" 11 >>> mystring += " world.a. "pi": 3. "list"].5 and later). "tuple")] mylist = ["List item 1". You can increment/decrement values using the += and -= operators respectively by the right-hand amount.g. Negative indexes count from the last item backwards (thus -1 is the last item) like so: . myvar Data types The data structures available in python are lists. objects are bound to names) with the _equals_ sign ("="). but new objects are bound to 17 # the old names. This works on many datatypes. You can also use multiple variables on one line. 15 # It doesn't violate strong typing because values aren't 16 # actually being assigned. and you can have quotation marks of one kind inside a string that uses the other kind (i. Use for to enumerate through members of a list. 2. Each %s gets replaced with an item from the tuple. 2] 8 >>> print mylist[1:] 9 [2.""" 10 11 # WARNING: Watch out for the trailing s in "%(key)s". 3. These statements' syntax is thus: ? .name. use if. Python supports Unicode out of the box.14] Strings Its strings can use either single or double quotation marks. Flow control statements Flow control statements are if. use range(<number>). 2. 3. 3." % {"noun": "test".14] 2 >>> print mylist[:] 3 ['List item 1'. using the syntax u"This is a unicode string". 3 * "-") 3 Name: Poromenos 4 Number: 3 5 String: --6 7 strString = """This is 8 a multiline 9 string. and you can also use dictionary substitutions. "verb": 13 "is"} 14 This is a test. you use the % (modulo) operator and a tuple. To obtain a list of numbers.1400000000000001] 4 >>> print mylist[0:2] 5 ['List item 1'. instead. There is no select. 12 >>> print "This %(verb)s a %(noun)s. Multiline strings are enclosed in _triple double (or single) quotes_ ("""). 3. and while. To fill a string with values." is valid). left to right. like so: ? >>>print "Name: %s\ 1 Number: %s\ 2 String: %s" % (myclass. for. "He said 'hello'.e.? 1 >>> mylist = ["List item 1". 2] 6 >>> print mylist[-3:-1] 7 ['List item 1'. Parameters are passed by reference. 9): 7 # "Break" terminates a for without 8 # executing the "else" clause. but immutable types (tuples. ints. 7. 1. 14 continue 15 else: 16 # The "else" clause is optional and is 17 # executed only if the loop didn't "break".1 rangelist = range(10) 2 >>> print rangelist 3 [0. 6 if number in (3. For example: ? . 3. so immutable types are replaced. the name of the argument is assigned a value. and binding another object to a variable discards the old one. Lambda functions are ad hoc functions that are comprised of a single statement. 8. 2. Functions can return a tuple (and using tuple unpacking you can effectively return multiple values). 9] 4 for number in rangelist: # Check if number is one of 5 # the numbers in the tuple. 4. 9 break 10 else: 11 # "Continue" starts the next iteration 12 # of the loop. 6. 18 pass # Do nothing 19 20 21 if rangelist[1] == 2: print "The second item (lists are 0-based) is 2" 22 23 elif rangelist[1] == 3: 24 print "The second item (lists are 0-based) is 3" 25 else: 26 print "Dunno" 27 28 while rangelist[1] == 1: 29 pass Functions Functions are declared with the "def" keyword. 5. 4. 7. It's rather useless here. For named arguments. This is because only the memory location of the item is passed. etc) *cannot be changed*. Optional arguments are set in the function declaration after the mandatory arguments by being assigned a default value. strings. 13 # as it's the last statement of the loop. 8 def passing_example(a_list. arg1. 2) 11 3 12 # This variable is shared by all classes.1 # Same as def f(x): return x + 1 2 functionvar = lambda x: x + 1 3 >>> print functionvar(1) 4 2 5 6 # an_int and a_string are optional. 3] 14 >>> my_int = 10 15 >>> print passing_example(my_list. arg2): 6 return self.common 15 10 16 >>> classinstance2. We can also bind arbitrary names to class instances. 2. An example follows: ? 1 class MyClass(object): 2 common = 10 3 def __init__(self): 4 self. 'A new item'] 19 >>> my_int 20 10 Classes Python supports a limited form of multiple inheritance in classes. an_int.myvariable 7 8 # This is the class instantiation 9 >>> classinstance = MyClass() 10 >>> classinstance. 13 >>> classinstance2 = MyClass() 14 >>> classinstance. a_string 12 13 >>> my_list = [1. 2. 'A new item']. Private variables and methods can be declared (by convention. 3. 2. an_int=2. this is not enforced by the language) by adding at least two leading underscores and at most one trailing one (e. 20 .common 17 10 18 # Note how we use the class name 19 # instead of the instance. they have default values 7 # if one is not passed (2 and "A default string". "A default string") 17 >>> my_list 18 [1. a_string="A default string"): a_list.myfunction(1.g.append("A new item") 9 an_int = 4 10 11 return a_list.myvariable = 3 5 def myfunction(self. 4. "__spam"). 3. my_int) 16 ([1. respectively). test member. Note 60 # that this will only be a member of classinstance. 2) 57 3 58 # This class doesn't have a . 50 def __init__(self. but from inside the class.common 39 50 40 41 # This class inherits from MyClass.>>> MyClass.myvariable = 3 52 print arg1 53 54 >>> classinstance = OtherClass("hello") 55 hello 56 >>> classinstance. arg1): 51 self.test = 10 62 >>> classinstance.common = 50 34 # This has not changed. so you can set 49 # instance variables as above.common 37 10 38 >>> classinstance2. The example 42 # class above inherits from "object". 61 >>> classinstance.common = 30 21 >>> classinstance. which makes 43 # it what's called a "new-style class".common 32 30 33 >>> MyClass. MyClassN) 46 class OtherClass(MyClass): 47 # The "self" argument is passed automatically 48 # and refers to the class instance. but 59 # we can add one to the instance anyway.myfunction(1.common 30 10 31 >>> classinstance2. because "common" is 35 # now an instance variable. MyClass2.common = 10 29 >>> classinstance. 26 # instead it will bind a new object to the old 27 # variable name.common 24 30 25 # This will not update the variable on the class.test 63 10 . 44 # Multiple inheritance is declared as: 45 # class OtherClass(MyClass1. 36 >>> classinstance.common 22 30 23 >>> classinstance2. 28 >>> classinstance. " 15 16 >>> some_function() 17 Oops. we're good. As an example. 13 14 print "We're done with that. Importing External libraries are used with the import [libname] keyword. here is how serializing (converting data structures to strings using the pickle library) with file I/O is used: ? . even # if a new exception is raised while handling. invalid. You can also use from [libname] import [funcname] for individual functions. 100) 5 >>> print randomint 6 64 File I/O Python has a wide array of libraries built in.Exceptions Exceptions in Python are handled with try-except [exceptionname] blocks: ? 1 def some_function(): try: 2 # Division by zero raises an exception 3 10 / 0 4 5 except ZeroDivisionError: 6 print "Oops. 9 pass 10 finally: 11 # This is executed after the code block is run 12 # and all exceptions have been handled. invalid." 7 else: 8 # Exception didn't occur. Here is an example: ? 1 import random 2 from time import clock 3 4 randomint = random.randint(1. 18 We're done with that. 'is'.dump(mylist.load(myfile) 21 myfile.close() 17 18 # Open the file for reading.dat") 20 loadedlist = pickle.close() 22 >>> print loadedlist 23 ['This'.close() 12 13 myfile = open(r"C:\\text.dat for writing. 5 myfile = open(r"C:\\binary.1 import pickle 2 mylist = ["This". 19 myfile = open(r"C:\\binary. • List comprehensions provide a powerful way to create and manipulate lists.write("This is a sample string") 11 myfile.read() 15 'This is a sample string' 16 myfile. "is".txt") 14 >>> print myfile. myfile) 7 myfile. • You can use del to delete variables or items in arrays. 13327] Miscellaneous • Conditions can be chained.txt". The letter r before the 4 # filename string is used to prevent backslash escaping. 4. 4. 1 < a < 3 checks that a is both less than 3 and greater than 1. They consist of an expression followed by a for clause followed by zero or more if or for clauses.close() 8 9 myfile = open(r"C:\\text. 13327] 3 # Open the file C:\\binary.dat". like so: ? . "w") 10 myfile. "w") 6 pickle. 3]]) 10 True 11 # This is because 4 % 3 = 1. but if you want to write to them you must declare them at the beginning of the function with the "global" keyword. 6. 3. local 10 # object instead of accessing the global one.1 >>> lst1 = [1. 4. Python knows that it an 9 # object will be bound to it later and creates a new. 3. 2. 3] if i == 4) 16 2 17 >>> del lst1[0] 18 >>> print lst1 19 [2. 13 14 # Check how many items have this property. it's a small catch that can get you if you don't know it). 9. 3] 2 >>> lst2 = [3. 18 number = 3 Epilogue This tutorial is not meant to be an exhaustive list of all (or even a subset) of Python. 3] 20 >>> del lst1 • Global variables are declared outside of functions and can be read without any special declarations. and 1 is true. 3] 7 # Check if an item has a specific property. 15] 5 >>> print [x for x in lst1 if 4 > x > 1] 6 [2. For example: ? 1 number = 5 2 3 def myfunc(): # This will print 5. 12. 8. 5] 3 >>> print [x * y for x in lst1 for y in lst2] 4 [3. 5. 4. 4. 4. 4. 10. 4. 9 >>> any([i % 3 for i in [3. 11 print number 12 13 number = 3 14 15 def yetanotherfunc(): 16 global number 17 # This will correctly change the global. so any() 12 # returns True. 8 # "any" returns true if any item in the list is true. Python has a vast . 15 >>> sum(1 for i in [3. 4 print number 5 6 7 def anotherfunc(): # This raises an exception because the variable has not 8 # been bound before printing. otherwise Python will bind that object to a new local variable (be careful of that. such as the excellent book Dive into Python. . Please leave comments if you believe there is something that could be improved or added or if there is anything else you would like to see (classes.array of libraries and much much more functionality which you will have to discover through other means. anything). I hope I have made your transition in Python easier. error handling.
Copyright © 2024 DOKUMEN.SITE Inc.