Simple 10-minute Python getting started tutorial and python getting started tutorial

Source: Internet
Author: User
Tags print format

Simple 10-minute Python getting started tutorial and python getting started tutorial

[Overview]

Python is a dynamic interpreted programming language. Python can be used on Windows, UNIX, MAC, and other operating systems, or on Java and. NET development platforms.

[Features]

1 Python is developed in C language, but Python does not have complex data types such as pointers in C language.

2. Python has a strong object-oriented feature and simplifies the implementation of object-oriented. It eliminates protection types, abstract classes, interfaces, and other object-oriented elements.

3. The Python code block is separated by spaces or tab indentation.

4 Python has only 31 Reserved Words and does not contain semicolons, in In, and end tags.

5. Python is a strongly typed language. After a variable is created, it corresponds to a data type. Different types of variables appearing in a unified expression need to be converted.

[Build a Development Environment]

1. You can download the installation package from www.python.org and install it through configure, make, and make install.

2. You can also download the ActivePython package at www.activestate.com. (ActivePython is a binary packaging of Python core and common modules. It is a Python Development Environment released by ActiveState. ActivePython makes Python installation easier and can be applied to various operating systems. ActivePython includes some common Python extensions and programming interfaces in Windows ). For activepython, if you are a Windows user, you can download the msipackage and install it. If you are a unixuser, download the tar.gz package and decompress it directly.

3. Python IDE, including PythonWin, Eclipse + PyDev plugin, Komodo, and EditPlus

[Version]

Python2 and python3 are currently two major versions.

We recommend using python2 in the following two cases:

1. When you cannot fully control the environment you are about to deploy;

2. When you need to use some specific third-party packages or extensions;

Python3 is officially recommended and fully supported in the future. Currently, many functions are only available in python3.

[Hello world]

1 create hello. py

2. Compile the program:
 

if __name__ == \'__main__\':  print "hello word"

3. Run the program:
 

python ./hello.py

[Note]

1. Line comment and segment comment are annotated with a space.

2. If you need to use Chinese comments in the code, you must add the following comments at the beginning of the python file:
 

# -* - coding: UTF-8 -* -

3. The following annotations are used to specify the interpreter.
 

#! /usr/bin/python

[File type]

1 Python file types are divided into three types: source code, byte code, and optimization code. These operations can be run directly without compilation or connection.

2. The source code uses the. py extension and is explained by python;

3. After the source file is compiled, a file with the extension of. pyc is generated, that is, the compiled byte file. Such files cannot be modified using a text editor. Pyc files are platform-independent and can be run on most operating systems. The following statement can be used to generate a pyc file:
 

import py_compilepy_compile.compile(‘hello.py')

4. The optimized source file is suffixed with. pyo, that is, the optimized code. It cannot be directly modified using a text editor. The following command can be used to generate a pyo file:
 

python -O -m py_complie hello.py

Variable]

1. Variables in python do not need to be declared. Variable assignment operations are performed even if the variables are declared and defined.

2. A new value assignment in python creates a new variable. Even if the variable name is the same, the variable IDs are different. You can use the id () function to obtain the variable identifier:
 

x = 1
print id(x)
x = 2
print id(x)

3. If the variable is not assigned a value, python considers that the variable does not exist.

4. variables defined outside the function can be called global variables. Global variables can be accessed by any function or external file in the file.

5. We recommend that you define global variables at the beginning of the file.

6. You can also put global variables in a special file and reference them through import:

The content in the gl. py file is as follows:
 

_a = 1_b = 2

Reference global variables in use_global.py:
 

import gl
def fun():
 print gl._a
 print gl._b
fun()

[Constant]

No reserved words for defining constants are provided in python. You can define a constant class to implement the constant function.
 

class _const:
 class ConstError(TypeError): pass
  def __setattr__(self,name,vlaue):
   if self.__dict__.has_key(name):
    raise self.ConstError, “Can't rebind const(%s)”%name
    self.__dict__[name]=value
import sys
sys.modules[__name__]=_const()

[Data type]

1. python numeric types include integer, long integer, floating point, Boolean, and plural.

2. python has no character type

3. python has no common types, and any type is an object.

4. To view the type of a variable, you can use the type class, which can return the type of the variable or create a new type.

5 python has three character string types: single quotation marks, double quotation marks, and three quotation marks. Single quotes and double quotes have the same effect. Python programmers prefer to use single quotes, while C/Java programmers prefer to use double quotes to represent strings. You can enter single quotation marks, double quotation marks, or line breaks among other characters.

[Operators and expressions]

1 python does not support auto-increment and auto-subtraction operators. For example, I ++/I-is incorrect, but I + = 1 is acceptable.

2. 1/2 is equal to 0.5 before python2.5, and 0 after python2.5.

3 is not equal! = Or <>

4 equals =

5. In a logical expression, "and" indicates logical and "or", not indicates non-logical

Control statement]

1. conditional statement:
 

if (expression):
   Statement 1
else:
   Statement 2

2 conditional statements:
 

if (expression):
  Statement 1
elif (expression):
  Statement 2
...
elif (expression):
  Statement n
else:
  Statement m 

3. Conditional nesting:
 

if (expression 1):
  if (expression 2):
   Statement 1
  elif (Expression 3):
   Statement 2
  ...
  else:
   Statement 3
elif (expression n):
   ...
else:
   ...

4. python does not have a switch statement.

5 loop statements:
 

While (expression ):... Else :...

6 loop statements:
 

For variable in set :... Else :...

7 python does not support loop statements like c (I = 0; I <5; I ++), but it can be simulated using range:
 

for x in range(0,5,2):  print x

[Array-related]

Tuple: a built-in data structure in python. Tuples are composed of different elements. Each element can store different types of data, such as strings, numbers, and even elements. Tuples are write-protected, that is, they cannot be modified after they are created. Tuples often represent a row of data, while elements in tuples represent different data items. You can think of tuples as unmodifiable arrays. An example of creating a tuples is as follows:
 

tuple_name=(“apple”,”banana”,”grape”,”orange”)

List: The list is similar to a group of elements. The list can be added, deleted, or searched, and the value of an element can be modified. A list is an array in the traditional sense. An example of creating a list is as follows:
 

list=[“apple”,”banana”,”grage”,”orange”]

You can use the append method to append an element to the end and use remove to delete the element.

3 dictionary: A collection composed of key-value pairs. Values in the dictionary are referenced by keys. Keys and values are separated by colons. Key-value pairs are separated by commas and included in a pair of curly braces. Example:
 

dict={“a”:”apple”, “b”:”banana”, “g”:”grage”, “o”:”orange”}

4. sequence: a sequence is a set of indexes and slices. Tuples, lists, and strings belong to sequences.

[Function related]

1. A python program consists of a package, a module, and a function. A package is a collection of modules. A module is a collection of functions and classes that handle a certain type of problem.

A 2-pack toolbox is used to complete a specific task.

The 3 package must contain a _ init _. py file, which is used to identify the current folder as a package.

4. python programs are composed of modules. The module organizes a set of related functions or code into a file. A file is a module. A module consists of code, functions, and classes. The import module uses the import Statement.

The role of the five packages is to reuse the program.

6. A function is a piece of code that can be called multiple times. The function definition example is as follows:
 

def arithmetic(x,y,operator):
  result={
   “+”:x+y,
   “-“:x-y,
   “*”:x*y,
   “/”:x/y
  }

7. return values can be controlled using return.

[String-related]

1. format the output:
 

format=”%s%d” % (str1,num)
print format

2. Merge strings with +:
 

str1=”hello”
str2=”world”
result=str1+str2

3. You can use the index/slice function or the split function to intercept strings.

4. truncate a string using slices:
 

word=”world”
print word[0:3]

5 python use = and! = To compare strings. If the two variables are of different types, the results will be different.

[File Processing]

1. Simple File Processing:
 

context=”hello,world”
f=file(“hello.txt”,'w')
f.write(context);
f.close()

2. You can use readline (), readlines (), and read functions to read files.

3. You can use the write () and writelines () functions to write files.

[Object and Class]

1. python defines a class with the class reserved words. The first character of the class name must be capitalized. When the type to be created by a programmer cannot be expressed by a simple type, you need to define the class and then create an object using the defined class. Definition example:
 
Class Fruit:
Def grow (self ):
Print "Fruit grow"

2. When an object is created, it contains three features: the handle, attributes, and methods of the object. How to create an object:
 

fruit = Fruit()
fruit.grow()

3. python does not have a modifier for the protection type.

The four methods can also be divided into public and private methods. Private functions cannot be called by functions other than the class, and private methods cannot be called by external classes or functions.

5. python converts a common function to a static method using the "staticmethod ()" or "@ staticmethod" command. Static methods are equivalent to global functions.

6. the python constructor is named _ init __and The Destructor is named _ del __

7 inherited usage:
 

class Apple(Fruit):  def …

[Connect to mysql]

1. It is very convenient to use the MySQLdb module to operate MySQL databases. The sample code is as follows:
 

import os, sys
import MySQLdb
try:
   conn MySQLdb.connect (host = 'localhost', user = 'root', passwd = '', db = 'address'
except Exception, e:
   print e
   sys.exit ()
cursor = conn.cursor ()
sql = 'insert into address (name, address) values (% s,% s)'
value = (("zhangsan", "haidian"), ("lisi", "haidian"))
try
   cursor.executemany (sql, values)
except Exception, e:
   print e
sql = ”select * from address”
cursor.execute (sql)
data = cursor.fetchall ()
if data
   for x in data:
     print x [0], x [1]
cursor.close ()
conn.close () 

Thank you!


Related Article

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.