Python Learning Notes (ii) Basic grammar

Source: Internet
Author: User
Learning Python, the basic grammar is not particularly difficult, with the basic knowledge of C, understanding is relatively easy. The main content of this article is the basic Python grammar, after learning, can be proficient in the use of good. (The development environment is still Python2.7, simple to use)
First, the basic knowledge
1, there is no need to pre-define the data type (this is debatable, let's say it), this is the most different from other languages (such as c,c++,c#,delphi, etc.)

Copy the Code code as follows:


>>> x=12
>>> y=13
>>> Z=x+y
>>> Print Z
25

Note: Although the variable does not need to be predefined, it must be assigned when it is used, otherwise the error is:

Copy the Code code as follows:


>>> Le
Traceback (most recent):
File " ", line 1, in
Le
Nameerror:name ' Le ' is not defined

2. Look at the type function of the variable ():

Copy the Code code as follows:


1 >>> type (x)
2

3. View the memory address function ID () of the variable:

Copy the Code code as follows:


>>> x=12
>>> y=13
>>> Z=x+y
>>> m=12
>>> print ' id (x) = ', id (x)
ID (x) = 30687684
>>> print ' id (m) = ', id (m)
ID (m) = 30687684
>>> print ' id (z) = ', id (z)
ID (z) = 30687528
>>> x=1.30
>>> print ' id (x) = ', id (x)
ID (x) = 43407128

From the above results can be found: the direction of the variable, the address is unchanged, in other words, the address value of the integer 12 is always the same, changing the direction of the variable (such as the address change of X);
4, Output function print ():

Copy the Code code as follows:


>>> x= ' Day '
>>> y=13.4
>>> print X,type (x)
Day
>>> print Y,type (y)
13.4

Comma operator (,): You can implement connection strings and numeric data.

Copy the Code code as follows:


>>> print ' x= ', 12
x= 12

Format control:%f floating-point number,%s string,%d double-precision floating-point number (this is consistent with the output of C).

Copy the Code code as follows:


>>> x=12
>>> y=13.0004
>>> z= ' Python '
>>> print "Output%d%f%s"% (x,y,s)
Output 13.000400 Python

5, Input function raw_input ():

Copy the Code code as follows:


>>> raw_input ("Input an int:")
Input an Int:12
' 12 '

Note: the Raw_input () input is a character type.
6, check Help function ():

Copy the Code code as follows:


>>> Help (ID)
Help on built-in function ID in module __builtin__:

ID (...)
ID (object), Integer

Return the identity of an object. This was guaranteed to be unique among
Simultaneously existing objects. (Hint:it ' s The object's memory address.)

Note: Python notes, #: only single-line comments are supported, and Python programming has a strict indentation format.

Second, function
1, function definition and its invocation:

Copy the Code code as follows:


#define FUNCTION:ADD (function description)
def add (x, y): #函数头部, note Colon, parameter x, y
Z=x+y #函数体
Return Z #返回值
#define MAIN function
def main ():
A=12
B=13
C=add (A, B) #函数调用, argument A, B
Print C
Main () #无参函数调用
print ' end1! '

Note: The similarities and differences between this part and C are:
1, the form participates in the use of the argument, no parameter function, has the parameter function, the default parameter and so on the rule is consistent.
such as def add (x,y=2), the call can be add (3) or add (3,4), add (y=34,x)
The 2,c parameter needs to specify the data type, which Python does not need.
The return value of 3,python allows for more than one. Such as:

Copy the Code code as follows:


def test (N1,N2):
Print N1,
Print N2
N=n1+n2
M=n1*n2
P=n1-n2
E=n1**n2
Return n,m,p,e
print ' Entry programme1 '
Sum,multi,plus,powl=test (2,10) #这个是C语言所没有的赋值方式
print ' sum= ', sum
print ' multi= ', multi
print ' plus= ', plus
print ' powl= ', Powl
Re=test (2,10)
Print re #数据类型为: ' Tuple '
Print Re[0],re[1],re[2],re[3]
print ' end1!\n '

Operation Result:

Copy the Code code as follows:


Entry programme
2 10
sum= 12
multi= 20
Plus=-8
Powl= 1024
2 10
(12, 20,-8, 1024)
12 20-8 1024
end!

2, Local variables:

Copy the Code code as follows:


Def f1 ():
X=12 #局部变量
Print X
def f2 ():
Y=13 #局部变量
Print Y
Def f3 ():
Print x #错误: No variable x is defined, not contradictory to "no predefined data types"
Print Y
def main ():
F1 ()
F2 ()
#f3 () #变量报错
Main ()
print ' end2! '

3, modify the value of the global variable:

Copy the Code code as follows:


Def modifyglobal ():
Global x #全局变量定义
print ' Write X =-1 '
X=-1
def main ():
# PRINTLOCALX ()
# printlocaly ()
# Readglobal ()
Modifyglobal ()

x=200
#y =100
print ' before modified global x= ',
Print X
Main ()
print ' after modified global x= ',
Print X

Operation Result:

Copy the Code code as follows:


>>>
Before modified global x= 200
Write X =-1
After modified global x=-1

Iii. Expressions and Branching statements
1, expression:
is a combination of numbers, operators, numeric groupings of symbol brackets, free variables, and constraint variables that can be obtained by means of a meaningful permutation of values. Indicates that there are usually two parts of operands and operators.
Classification: arithmetic expressions; relational expressions, logical expressions (And/or/not)
2,IF Branch Statements:
1) Form one: (If :)

Copy the Code code as follows:


>>> sex= "Male"
>>> if sex== ' male ':
print ' man! '
#此处有两次回车键
man!
>>>

2) Form two: (If : Else (if :))

Copy the Code code as follows:


Sex=raw_input (' Please input your sex: ')
If sex== ' m ' or sex== ' male ':
print ' man! '
Else
print ' woman! '

Operation Result:

Copy the Code code as follows:


>>>
Please input your Sex:male
man!

3) Form three: (If : elif : Else)) (This is the form that Python has and C does not)

Copy the Code code as follows:


Count=int (raw_input (' Please input your score: '))
If count>=90:
print ' Excellent! '
Elif count>=80:
print ' Fine! '
Elif count>=70:
print ' Qualified! '
Elif count>=60:
print ' Pass! '
Else
print ' Less than lattice! '

Operation Result:

Copy the Code code as follows:


>>>
Please input your score:90
Excellent!

Note: Python does not have a switch statement.

Four, the Loop statement:
Background: In the design of the time, often encounter some statements are repeatedly executed, such code is very long and inefficient, very not intuitive, then you should consider using the loop body to achieve.
1,while statement: With C in the expression of difference, C has while and do......while form; Python: While with while......else ... Form
1) While in the form of:

Copy the Code code as follows:


I=1
While i<5:
print ' Welcome you! '
I=i+1

2) While......else ... In the form of:

Copy the Code code as follows:


I=1
While i<5:
print ' Welcome you! '
I=i+1
Else
Print "While over!" #循环正常结束

Note: If the while unhealthy state ends (that is, does not end with a loop condition), the Else statement does not execute. As follows:

Copy the Code code as follows:


I=1
While i<5:
print ' Welcome you! '
I=i+1
If i==2:
print ' While ... '
Break
Else
Print "While over!"

Operation Result:

Copy the Code code as follows:


1 >>>
2 Welcome you!
3 while ...

Add:
Continue statement: When it appears in the while loop body, the statement under this loop continue is not executed and goes directly to the next loop.

Copy the Code code as follows:


I=1
While i<=5:
If i==2 or i==4:
print ' While......continue '
I=i+1
Continue
print ' Welcome you! '
I=i+1
Else
Print "While over!"

Operation Result:

Copy the Code code as follows:


>>>
Welcome you!
While......continue
Welcome you!
While......continue
Welcome you!
While over!

Five, Summary:

This article introduces Python variables, input and output functions, expressions, basic statements (branching and looping) and other related uses of knowledge, through practice, should have a preliminary understanding of Python.

  • 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.