Simple Python Getting Started Guide

Source: Internet
Author: User
This article is a simple guide to getting started with Python. The original article is quite popular on the internet. I will describe some basic knowledge using the instance code. For more information, see First test knife

If you want to learn the Python language, you cannot find a brief and comprehensive Getting Started Tutorial. This tutorial will take you to the door of Python in ten minutes. The content in this article is between the tutorial (Toturial) and the quick query manual (CheatSheet), so it only contains some basic concepts. Obviously, if you want to learn a language well, you still need to practice it yourself. Here, I will assume that you already have a certain programming foundation, so I will skip most of the content related to non-Python. This article highlights important keywords so that you can easily see them. In addition, due to the limited length of this tutorial, I will directly use the code to describe it with a few comments.
Python language features

Python is a type with strong (that is, the variable type is mandatory), dynamic, implicit (variable declaration is not required), and case sensitive (var and VAR represent different variables) and object-oriented programming languages (all objects.


Get help

You can easily get help through the Python interpreter. If you want to know how an object works, you need to call help ()! There are also some useful methods, dir () will show all the methods of this object, and. _ Doc _ will display its document:

>>> help(5)Help on int object:(etc etc) >>> dir(5)['__abs__', '__add__', ...] >>> abs.__doc__'abs(number) -> number Return the absolute value of the argument.'


Syntax

There is no mandatory statement termination character in Python, and the code block is indicated by indentation. Indentation indicates the beginning of a code block, and reverse indentation indicates the end of a code block. The declaration ends with a colon (:) and an indent level is enabled. A single line comment starts with the # Character, and a multi-line comment appears as a multi-line string. Assign values (in fact, bind an object to a name) through the equal sign ("="), the double equal sign ("=") is used for equal judgment, "+ =" and "-=" are used to increase/decrease operations (the increase/decrease value is determined by the value on the right of the symbol ). This applies to many data types, including strings. You can also use multiple variables on one row. For example:

>>> myvar = 3>>> myvar += 2>>> myvar5>>> myvar -= 1>>> myvar4"""This is a multiline comment.The following lines concatenate the two strings.""">>> mystring = "Hello">>> mystring += " world.">>> print mystringHello world.# This swaps the variables in one line(!).# It doesn't violate strong typing because values aren't# actually being assigned, but new objects are bound to# the old names.>>> myvar, mystring = mystring, myvar


Data type

Python has three basic data structures: list, tuple, and dictionaries, while set) it is included in the collection Library (but it has become a Python built-in type since Python2.5 ). A list is similar to a one-dimensional array (you can also create a list similar to a multi-dimensional array). A dictionary is an array with an association relationship (usually called a hash table ), the tuples are unchangeable one-dimensional arrays ("arrays" in Python can contain any type of elements, so that you can use mixed elements, such as integers, strings, or nested include lists, dictionaries, or tuples ). The index value (subscript) of the first element in the array is 0, and the index value of the negative number can be used to access the array element from the back and forward.-1 indicates the last element. Array elements can also point to functions. Let's take a look at the following usage:

>>> sample = [1, ["another", "list"], ("a", "tuple")]>>> mylist = ["List item 1", 2, 3.14]>>> mylist[0] = "List item 1 again" # We're changing the item.>>> mylist[-1] = 3.21 # Here, we refer to the last item.>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}>>> mydict["pi"] = 3.15 # This is how you change dictionary values.>>> mytuple = (1, 2, 3)>>> myfunction = len>>> print myfunction(mylist)3

You can use the: Operator to access a segment in the array. if it is null on the left, it indicates that the first element starts. Similarly, if it is null on the right, it indicates that the last element ends. A negative index indicates the position of the forward number (-1 is the last item), for example:

>>> mylist = ["List item 1", 2, 3.14]>>> print mylist[:]['List item 1', 2, 3.1400000000000001]>>> print mylist[0:2]['List item 1', 2]>>> print mylist[-3:-1]['List item 1', 2]>>> print mylist[1:][2, 3.14]# Adding a third parameter, "step" will have Python step in# N item increments, rather than 1.# E.g., this will return the first item, then go to the third and# return that (so, items 0 and 2 in 0-indexing).>>> print mylist[::2]['List item 1', 3.14]


String

Strings in Python are marked with single or double quotation marks, you can also use another identifier (for example, "He said 'hello') in a string marked by a specific identifier '. "). Multiple-line strings can be marked by three consecutive single quotes ("') or double quotes. Python can use unicode strings using the syntax u "This is a Unicode string. If you want to fill the string with variables, you can use the modulo operator (%) and a tuple. The usage is to use % s from left to right in the target string to indicate the position of the variable, or use a dictionary instead. The example is as follows:

>>>print "Name: %s\Number: %s\String: %s" % (myclass.name, 3, 3 * "-")Name: PoromenosNumber: 3String: --- strString = """This isa multilinestring.""" # WARNING: Watch out for the trailing s in "%(key)s".>>> print "This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"}This is a test.


Process control

In Python, if, for, and while can be used for process control. Python does not have a select statement. Instead, if is used. Use for to enumerate the elements in the list. If you want to generate a list composed of numbers, you can use range ( ) Function. The syntax examples of these declarations are as follows:

rangelist = range(10)>>> print rangelist[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]for number in rangelist:  # Check if number is one of  # the numbers in the tuple.  if number in (3, 4, 7, 9):    # "Break" terminates a for without    # executing the "else" clause.    break  else:    # "Continue" starts the next iteration    # of the loop. It's rather useless here,    # as it's the last statement of the loop.    continueelse:  # The "else" clause is optional and is  # executed only if the loop didn't "break".  pass # Do nothing if rangelist[1] == 2:  print "The second item (lists are 0-based) is 2"elif rangelist[1] == 3:  print "The second item (lists are 0-based) is 3"else:  print "Dunno" while rangelist[1] == 1:  pass


Function

The function is declared using the "def" keyword. Optional parameters appear in the function declaration in the form of a set followed by required parameters. optional parameters can be assigned a default value in the function declaration. A value must be assigned to a named parameter. The function can return a single tuple (multiple values can be effectively returned by using the tuples for package splitting ). A Lambda function is a special function composed of individual statements. parameters are passed through references, but they cannot be changed for immutable types (such as tuples, integers, and strings. This is because only the memory address of the variable is passed and the variable can be bound to an object only after the old object is discarded. Therefore, the unchangeable type is replaced rather than changed: although the parameter format passed by Python is essentially reference transfer, it will produce the effect of value transfer ). For example:

# The function is equivalent to def funcvar (x): return x + 1 funcvar = lambda x: x + 1 >>> print funcvar (1) 2 # an_int and a_string are optional parameters, they have the default value # if only one parameter is specified when passing_example is called, an_int defaults to 2 and a_string defaults to A default string. If the first two parameters are specified when passing_example is called, a_string is still A default string by default. # A_list is a required parameter because it does not specify the default value. Def passing_example (a_list, an_int = 2, a_string = "A default string"): a_list.append ("A new item") an_int = 4 return a_list, an_int, a_string >>> my_list = [1, 2, 3] >>> my_int = 10 >>> print passing_example (my_list, my_int) ([1, 2, 3, 'A new item'], 4, "A default string") >>> my_list [1, 2, 3, 'a new item'] >>> my_int10


Class

Python supports limited multi-inheritance forms. Private variables and methods can be declared by adding at least two leading underlines and at most one trailing underline (for example, "_ spam", which is just a convention, rather than a mandatory requirement of Python ). Of course, we can also give the class instance any name. For example:

class MyClass(object):  common = 10  def __init__(self):    self.myvariable = 3  def myfunction(self, arg1, arg2):    return self.myvariable   # This is the class instantiation>>> classinstance = MyClass()>>> classinstance.myfunction(1, 2)3# This variable is shared by all classes.>>> classinstance2 = MyClass()>>> classinstance.common10>>> classinstance2.common10# Note how we use the class name# instead of the instance.>>> MyClass.common = 30>>> classinstance.common30>>> classinstance2.common30# This will not update the variable on the class,# instead it will bind a new object to the old# variable name.>>> classinstance.common = 10>>> classinstance.common10>>> classinstance2.common30>>> MyClass.common = 50# This has not changed, because "common" is# now an instance variable.>>> classinstance.common10>>> classinstance2.common50 # This class inherits from MyClass. The example# class above inherits from "object", which makes# it what's called a "new-style class".# Multiple inheritance is declared as:# class OtherClass(MyClass1, MyClass2, MyClassN)class OtherClass(MyClass):  # The "self" argument is passed automatically  # and refers to the class instance, so you can set  # instance variables as above, but from inside the class.  def __init__(self, arg1):    self.myvariable = 3    print arg1 >>> classinstance = OtherClass("hello")hello>>> classinstance.myfunction(1, 2)3# This class doesn't have a .test member, but# we can add one to the instance anyway. Note# that this will only be a member of classinstance.>>> classinstance.test = 10>>> classinstance.test10


Exception

Exceptions in Python are handled by try-exclude T [exceptionname] Blocks. for example:

def some_function():  try:    # Division by zero raises an exception    10 / 0  except ZeroDivisionError:    print "Oops, invalid."  else:    # Exception didn't occur, we're good.    pass  finally:    # This is executed after the code block is run    # and all exceptions have been handled, even    # if a new exception is raised while handling.    print "We're done with that." >>> some_function()Oops, invalid.We're done with that.


Import

External libraries can be imported using the import [libname] keyword. You can also use from [libname] import [funcname] to import the required functions. For example:

import randomfrom time import clock randomint = random.randint(1, 100)>>> print randomint64


File I/O

Python provides many built-in function libraries for file processing. For example, the following example shows how to serialize a file (convert the data structure to a string using the pickle Library ):

import picklemylist = ["This", "is", 4, 13327]# Open the file C:\\binary.dat for writing. The letter r before the# filename string is used to prevent backslash escaping.myfile = open(r"C:\\binary.dat", "w")pickle.dump(mylist, myfile)myfile.close() myfile = open(r"C:\\text.txt", "w")myfile.write("This is a sample string")myfile.close() myfile = open(r"C:\\text.txt")>>> print myfile.read()'This is a sample string'myfile.close() # Open the file for reading.myfile = open(r"C:\\binary.dat")loadedlist = pickle.load(myfile)myfile.close()>>> print loadedlist['This', 'is', 4, 13327]


Miscellaneous

Value determination can be linked. for example, 1 can use del to delete variables or elements in arrays.
List Comprehension provides a powerful tool for creating and operating lists. The list derivation is composed of an expression and a for statement that is followed by this expression. the for statement can also contain 0 or more if or for statements. the following example shows the for statement:

>>> lst1 = [1, 2, 3]>>> lst2 = [3, 4, 5]>>> print [x * y for x in lst1 for y in lst2][3, 4, 5, 6, 8, 10, 9, 12, 15]>>> print [x for x in lst1 if 4 > x > 1][2, 3]# Check if an item has a specific property.# "any" returns true if any item in the list is true.>>> any([i % 3 for i in [3, 3, 4, 4, 3]])True# This is because 4 % 3 = 1, and 1 is true, so any()# returns True. # Check how many items have this property.>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 4)2>>> del lst1[0]>>> print lst1[2, 3]>>> del lst1

Global variables are declared outside the function and can be read without any special declaration. However, if you want to modify the value of global variables, the global keyword must be used at the beginning of the function. otherwise, Python processes the variable according to the new local variable ). For example:

  number = 5     def myfunc():    # This will print 5.    print number     def anotherfunc():    # This raises an exception because the variable has not    # been bound before printing. Python knows that it an    # object will be bound to it later and creates a new, local    # object instead of accessing the global one.    print number    number = 3     def yetanotherfunc():    global number    # This will correctly change the global.    number = 3


Summary

This tutorial does not cover all the content of the Python language (even a small part cannot be called ). Python has many libraries and many features to learn. to learn Python well, you must use other methods, such as reading Dive into Python. I hope this tutorial will give you a good start Guide. If you think there is something worth improving or adding in this article, or you want to know about Python, leave a message.

This tutorial is applicable to short e-books. The various Python best practices provided by the e-book follow-up are available in an independent ebook, and interested students can buy in https://leanpub.com/learn-python. After purchase, you can get updates for free.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.