Beginners Learn python-Basics (2)

Source: Internet
Author: User

Variable name:
1) must start with a character or underscore
2) starting with a single underscore (_FO) represents a class attribute that cannot be accessed directly, requiring access to the interface provided by the class
3) The private member of the class that starts with a double underscore (__foo)
4) A double-underscore (__foo__) and end-specific identifier that represents a special method in Python, such as __init__ () represents the constructor of a class

Global variables
Keyword Global
_num = 12def myfunction (): Global _num# refers to globally variable num = _num + 1print ' myfunction num= ' + str (num) myfunction ()

The representation function of a string
STR (): Converts a value into a reasonably-form string for the user to understand
Repr (): Creates a string that represents a value in the form of a legitimate Python expression.
For example:
>>> print repr (123L) 123l>>> print str (123L) 123

Input and output
Output: Print statement
Inputs: Input () and raw_input () functions
Input () defaults read-in user data to Python expression
Raw_input () Converts the read-in data to a string

Operator

1)

>>> 5/60>>> 5//60>>> 5.0/60.8333333333333334>>> 5.0//60.0
2)
>>> from __future__ import division>>> 5/60.8333333333333334>>> 5//60>>> 5.0/ 60.8333333333333334>>> 5.0//60.0
3)
>>> -3**2-9>>>-(3**2)-9
The Power operator (* *) takes precedence over the inverse operator (unary subtraction operator), so -3**2 and-(3**2) are equivalent.

Precedence of Operators
Arithmetic operators > Relational operators > Logical operators

True and false are only an aesthetic modification of 1 and 0, but the substance is the same. Refer to the following example:
>>> True = = 1true>>> False = = 0True

Loop Statement instance:
1) while
i = 1while i <= 5:    print (' the ' + str (i) + ' s print. ')    i + = 1else:    print (' End ... ')

2) for
Array = [(1, 2), (3, 4), (5, 6)]for (x, y) in array:    print (x, y);

Iterators
For line in open (' Test.txt '):p rint Line

Parallel iterations
1)
names = [' admin ', ' guest ']passwords = [' admin ', ' guest ']for I in range (len (names)):    print ("Name:%s, Password:%s"% ( Names[i], passwords[i]))

2)
names = [' admin ', ' guest ']passwords = [' admin ', ' guest ']for name, password in zip (names,passwords):    print ("Name:%s, p Assword:%s "% (name, password))
Zip "Compresses" the two sequences together and returns a list of tuples.

Numbering iterations
names = [' admin ', ' guest ']for index, name in enumerate (names):    if ' admin ' in Name:        Names[index] = ' root '        print ("Index:%s, Name:%s"% (index, name)) print (names)
The primary function of the enumerate is to iterate over the index value pairs where the index is provided.

Some statements
Break
The break keyword appears in a loop statement to jump out of the entire loop. If the break keyword appears in a nested loop, it indicates that the nested loop is out.
Continue
Skip this cycle and proceed to the next loop
Pass
means nothing to do, similar to a placeholder
Del:
You can delete objects that are no longer in use. Using the DEL statement will not only remove the reference to an object, but it will also remove the name itself.
1)
Name = ' admin ' del nameprint name
This program will result in error: Nameerror:name ' name ' is not defined
2)
Name = ' Admin ' key = Namedel nameprint key
This program runs the result for admin. Removing the name does not affect the key. Because Python removes only the name, not the value itself.
Exec:
exec "print ' Hello '"
The result of the execution is: Hello

Functions and modules
Python programs consist of packages, modules (module), and functions.
A package is a collection of modules that are made up of a series. A module is a collection of functions and classes that handle a class of problems. Python provides a number of useful toolkits, such as string processing, image processing, Web applications, and so on.
The package must contain at least one __init__.py file, and the contents of the file can be empty. __init__.py is used to identify the current folder as a package.

Function
1) definition
def function_name (arg1,arg2,....): Statementreturn value
Where the return value is not required. If there is no return statement, the Python default return value is None.
Example:
DEF login (username, password):    if (username = = ' admin ') and (password = = ' admin '):        print ' login success! '    else:        print ' Login error ... '
Can be called using the following statement:
Login (' admin ', ' admin ')

2) Function shape participates in default parameter values
There are two ways to pass parameters: value passing and reference passing. Parameters are specified within the parentheses of the function definition, separated by commas, and when the function is called, it is also necessary to provide the value in the same way (the parameter name in the function is a formal argument, and the value provided to the function call is called an argument).
2.1) Default parameter values:
def login (username= "Guest", password= "Guest"):    if (username = = ' admin ') and (password = = ' admin '):        print ' login s Uccess! '    else:        print ' Login error ... '

This is called using the following invocation methods:
Login (' admin ', ' admin ') login (' admin ') login (password= ' admin ') login ()

The results returned are as follows:
Login Success!login error.....login error.....login error .....
The first method provides two parameters, overriding the default of two values.
The second way provides one, so username is overwritten by admin, but password uses the default guest.
The third method specifies password as admin, but username uses the default guest
The four-way two parameters all use the default values.

2.2) List parameter values
def print_array (names=[]):    for name in Names:        print (name) keys = [' admin ', ' guest ']print_array (keys)

2.3) variable length parameter value
def print_names (* names): For    name in names:        print (name) print_names (' root ') print_names (' admin ', ' guest ')

Because the parameter uses the * identifier, the actual parameters passed in are "encapsulated" into a tuple.

2.4) dictionary type parameter value
def print_key_value (* * key_value):    keys = Key_value.keys () for    key in keys:        print ("Key:%s, Value:%s"% (key, Key_value[key]) print_key_value (username = ' admin ', password = ' admin ')
Operation Result:
Key:username, Value:adminkey:password, value:admin

Reprint Please specify the Source:http://blog.csdn.net/iAm333

Beginners Learn python-Basics (2)

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.