Beginners Learn python-Basics (2)

Source: Internet
Author: User
Tags arithmetic operators function definition

Variable name:
1) must start with a character or underscore
2) A single underscore (_FO) indicates a class attribute that cannot be directly visited, and requires an 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 the end of an identifier that represents a special method in Python, such as __init__ () that 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. Represents a value in the form of a valid Python expression.
Like what:
>>> print repr (123L) 123l>>> print str (123L) 123

Input and output
Output: Print statement
Inputs: Input () and raw_input () functions
Input () will read the user data implicitly feel 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. Consider the following examples:

>>> 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
A breakkeyword appears in a loop statement. means to jump out of the loop. Assume that breakkeyword occurs in a nested loop. Indicates that the nested loop is out of bounds.
Continue
Skip this cycle. Continue to the next cycle
Pass
means nothing to do, similar to a placeholder
Del:
Ability to 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
The execution of this program will result in an error: Nameerror:name ' name ' is not defined
2)
Name = ' Admin ' key = Namedel nameprint key
This program executes 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 operation 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 include at least one __init__.py file, and the contents of the file can be empty. The __init__.py is used to identify the current directory as a package.



Function
1) definition

def function_name (arg1,arg2,....): Statementreturn value
Of The return value is not required.

Assuming there is no return statement, the Python default return value is None.


Examples:

DEF login (username, password):    if (username = = ' admin ') and (password = = ' admin '):        print ' login success! '    else:        print ' Login error ... '
Can be invoked using the following statement, for example:
Login (' admin ', ' admin ')

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

Call it down using the following methods, for example:
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 of the parameters. Overrides the default of two values.
Another way to provide one, so username is covered by admin. However, password uses the default guest.
The third Way specifies the password as admin. But username uses the default guest
The default value is used for all two of the four-way parameters.

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

2.3) Variable length parameters
def print_names (* names): For    name in names:        print (name) print_names (' root ') print_names (' admin ', ' guest ')

Because the parameters use the * identifier, the actual number of passes passed in is "encapsulated" into a tuple.

2.4) dictionary type number of references
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 ')
Execution Result:
Key:username, Value:adminkey:password, value:admin

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

Beginners Learn python-Basics (2)

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.