Python first bullet Quick start

Source: Internet
Author: User

Quick Start:
The 1.python print statement, which is used in conjunction with the sub-payment format operator (%), implements the string substitution function.

Print "%s is number%d"% ("Python", 1)

%s represents a string to replace;
%d is replaced by an integral type;
%f is replaced by a floating-point type;

The 2.python statement also supports output to a file redirection. Symbols >> used to orient the output.
>>> Import Sys
>>> log = open ('/tmp/myprint.log ', ' a ')
>>> Print >> log, ' Fail error:invalid input '
>>> Log.close ()

3. Program input and Raw_input () built-in functions
The Raw_input () built-in function that reads the standard input and assigns the read data to the specified variable.
>>> phone=raw_input (' Please input your phone number: ')
Please input your phone number:18621530000
>>> print ' You phone number is: ', phone
You phone number is:18621530000

4.python annotations
>>> #This is a comment//This behavior comment statement
... print ' This is a comment test '
This is a comment test

5.python operator
+
-
*
/
//
%
**

6. Comparison operator, which returns a Boolean value based on the value of an expression.
<
<=
>
>=
==
! = (Not equal to)
<> (Not equal to, this method is slowly again eliminated)

7.python Logic Operators
and
Or
Not

8. Variables and Assignments
Python is a dynamic language, meaning that you do not need to declare the type of the variable beforehand. The type and value of the variable are initialized at the moment of assignment.

9. Digital
The five basic numeric types supported by Python:
Integral type (int)
Long integer type
Boolean (BOOL) True is treated as an integral type 1,faule as an integer value of 0.
Floating-point value (float)
Negative number (complex)

10. Strings are defined as the character set between quotation marks. Python supports the use of paired single or double quotes, and three quotation marks can be used to contain special characters. Use the index operator ([]) and the Slice operator ([:]) to get substrings. The substring has its own index rule:
The index of the first character is 0,
The index of the last character is-1.

The Plus + is used for string join operations, and the asterisk * is used for string repetition.
>>> a= ' Pythonchina '
>>> a*2
' Pythonchinapythonchina '
>>> A[2]
' t '
>>> A[2:5]
' Tho '
>>> A[3:]
' Honchina '

11. List and Ganso
Lists and Ganso can be used as normal "arrays", which can hold any type of Python object. As well as arrays, elements are accessed through a numeric index starting at 0, but lists and Ganso can store different types of objects. There are several important differences between the list and the Ganso, the list element is wrapped with [], the number of elements and the value of the element can be changed. Ganso is wrapped with parentheses () and cannot be changed. Ganso can be viewed as a read-only list. A subset can be obtained by slicing operations [],[:].

>>> alist = [1,2,5, ' A ', ' abc ']
>>> Alist[3]
A
>>> type (alist)
<type ' list ' >
>>> atuple= (' Rockets ', ' 2 ', ' 1.24 ', ' a+1.8 ')
>>> Atuple[-1]
' a+1.8 '
>>> type (atuple)
<type ' tuple ' >

12. Dictionaries
A dictionary is a mapping data type in Python that works like an associative array or hash table in Perl. Composed of key-value (ker-value) pairs. Almost all Python objects can be used as keys.
>>> adict = {' Host ': ' Earth '}
>>> adict[' port '] = 80
>>> adict
{' Host ': ' Earth ', ' Port ': 80}
>>> Adict.keys ()
[' Host ', ' Port ']

>>> for key in Adict:
... print key, Adict[key]
...
Host Earth
Port 80

13. code block and indent alignment
Code blocks are more readable by indentation-aligned expression code logic. And indentation makes it clear which expression block a statement belongs to.

14.if statements
If expression: The value of the//expressions is not 0 or Boolean true, then If_suite is executed.
If_suite

#!/usr/bin/env python
# Filename:if.py

Number=23
Guess=int (Raw_input (' Enter an Integer: '))

If Guess==number:
print ' guess is equal number '
Elif Guess<number:
print ' guess is not big than number '
Else
print ' No, it's a little lower than that '

print ' Done '

15.while Cycle
The syntax of a standard while conditional loop statement is similar to the IF, as follows:
While expression:
While_suite

The statement while_suite is executed continuously until the value of the expression becomes 0 or false, and then Python executes the next code. Similar to the IF statement, the expression in Python's while statement does not need to be enclosed in parentheses.
>>> counter=0
>>> While counter < 3:
... print ' Loop #%d '% (counter)
... counter +=1
...
Loop #0
Loop #1
Loop #2

16.for Loop and Range () built-in functions
The For loop in Python is not the same as a traditional for loop, and it is more like a foreach iteration in a shell script. A For loop in Python can accept an iterative object (such as a sequence or iterator) as an argument, iterating over one of the elements at a time.
>>> for item in {' Email ', ' net-surfing ', ' TV '}:
.... Print item
...
Tv
Net-surfing
Email

After you add ', ' to the print statement, you can have the output on the same line.

>>> for I in range (5):
... print I
...
0
1
2
3
4

Note: the range () built-in function is used to generate a range of values.
>>> a= ' abc '//For string iterations
>>> for I in range (5):
... print I,
...
0 1 2) 3 4

The range function is often used with the Len () function for the string index, where we want to display each element and its index value.
>>> for I in range (Len (a)):
... print a[i], ' (%d) '% i
...
A (0)
B (1)
C (2)


seq = ["One", "one", "three"]
For I, element in enumerate (seq):
Seq[i] = '%d,%s '% (I, seq[i])
Print seq


17. List resolution
We can use a for loop in a row to put all the values in a list.
squared=[x * * 2 for X in range (4)]
For i in squared:
Print I,

18. Files and built-in functions, open (), file ()
The method properties of a file object must be accessed through the period property identification method.
Properties are data-related items, properties can be simple data values, or they can be execution objects, such as functions and methods. Many classes, modules, files, and complex numbers have properties, how do we Access object properties? Use the period notation, which is the addition of a period (.) between the object name and the property name:
Object.attribute
#!/usr/bin/python

filename = raw_input (' Enter file name: ')
Fobj=open (filename, ' R ')
For Eachline in Fobj:
Print Eachline,
Fobj.close ()

19. Errors and exceptions
Syntax errors are checked at compile time, but Python also allows the program to detect errors while it is running. When an error is detected, the Python interpreter throws an exception and displays the details of the exception. To add error detection and exception handling to your code, just encapsulate them in the try-except statement. The code group after try is the code you intend to manage. The code group after except is your code that handles the error.

#!/usr/bin/python
Try
filename = raw_input (' Enter file name: ')
Fobj=open (filename, ' R ')
For Eachline in Fobj:
Print Eachline,
Fobj.close ()
Except IOError, E:
print ' File Open error: ', E

20. Functions
Python is called by reference, which means that changes to the parameters within the function affect the original object.
How do I define a function?
def function_name ([arguments]):
"Optional documentation string"
Function_suite
Defines a function syntax that is defined by the DEF keyword and followed by the function name. With the addition of several parameters required by the function, the function arguments are optional, which is why they are placed in parentheses.

def addme2me (x):
' Apply + operation to argument '
return (x + x)
Print Addme2me (' Pythonchina ')
Print Addme2me (5.25)
Print Addme2me ([-1, ' abc '])

The default parameter, the function parameter can have a default value, if provided with a default value, in the function definition, the parameter is provided in the form of an assignment statement. In fact, this is just the syntax that provides the default argument, which indicates that when the function call does not provide this argument, he takes the value as the default value.
def foo (debug=true):
If debug:
print ' in debug mode '
print ' Done '
Foo ()
Foo (False)

21. Class
Class is the core of object-oriented programming, which plays the role of related data and logical containers. They provide a blueprint for creating real ' objects ' because Python does not require you to program in an object-oriented manner.
How do I define a class?
Class ClassName (Base_class[es]):
"Optional documentation string"
Static_member_declarations
Method_declarations

Class Fooclass (object):
"" "My very first Class:fooclass" ""
version= 0.1
def _int_ (self, nm= ' Joe Doe '):
"" "Constructor" ""
Self.name = NM # class instance (data) attribute
print ' Created A class instance for ', NM
def showname (self):
"" "Display instance attribute and class name" ""
print ' Your name is ', Self.name
print ' My name is ', self._class_._name_
def showver (self):
"" "Display Class (Static) attribute" ""
Print Self.version # References Fooclass.version
def addme2me (self,x):
"" "Apply + operation to argument" "" "
Return x+x

In the above class, we define a static variable version, which will be shared by all instances and 4 methods. These show* () methods do not do anything useful, just output the corresponding information. The _init_ () method has a special name, and it is a special method for all names to start and end with two underscores.

When an instance of a class is created, the _init_ () method is executed automatically after the class strength is created, similar to the constructor. _init_ () can be used as a constructor, and it does not create an instance-it is just the first method that executes after your object is created. Its purpose is to perform some of the necessary initialization work for the object by creating its own _init_ () method. In this example, we initialize a class instance property named Name, which exists only in the class instance and is not part of the actual class itself. _init_ () requires a default parameter, and you will undoubtedly notice that each of these methods has a parameter of self.

What is self? It is a reference to the instance itself.

How to create a class instance

#-*-Coding:utf-8-*-

__author__ = ' Xudongqi '
class people:
Name = ' '
Age = 0
__weight = 0
#定义基本属性, private properties cannot be accessed directly outside.

#定义构造方法
def __init__ (self,n,a,w):
Self.name = n
Self.age = A
Self.__weight = W
def speak (self):
Print ("%s is speaking:i am%d years old"% (self.name,self.age))


p = people (' Tom ', 10,30)
P.speak ()


22. Module
A module is a form of organization that organizes Python code that is related to each other into separate files. Module executable code, functions and classes, or a combination of these things.
When you create a Python source file, the name of the module is the file name without the. py suffix. Once a module is created, you can import the module from another module using an import statement.

How to import Modules
Import Module_name

How to access a module function or access a module variable
Once the import is complete, the properties of a module (functions and variables) can be accessed through the familiar period property identifier.
Module.function ()
Module.variable

Useful functions:
Dir ([obj])
Help ([obj])
int ([obj])
Len ([obj])
Open (Fn,mode)
Range ([Start,]stop[,step])
Raw_input (str)
STR (obj)
Type (obj)



Python first bullet Quick start

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.