Python Learning Notes (ii) basic grammar _python

Source: Internet
Author: User

Learning Python, basic grammar is not particularly difficult, with the basic knowledge of C, easy to understand. The main content of this article is Python basic grammar, after learning, can be used skillfully. (The development environment is still Python2.7, simple to use)
First, the basic knowledge
1, there is no need to define the data type (this argument is debatable, let's say), which is the biggest difference from other languages (e.g. c,c++,c#,delphi, etc.)

Copy Code code as follows:

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

Note: Although variables need not be predefined, they must be assigned when they are used, or they will be an error:

Copy Code code as follows:

>>> Le
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
Le
Nameerror:name ' Le ' is not defined

2, view the type function of the variable ():

Copy Code code as follows:

1 >>> type (x)
2 <type ' int ' >

3, view the variable's memory address function ID ():

Copy 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: variable direction, address unchanged, in other words, the integer 12 address value is always the same, the change is the point of the variable (such as the address of X changes);
4, Output function print ():

Copy Code code as follows:

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

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

Copy Code code as follows:

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

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

Copy 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 Code code as follows:

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

Note: the Raw_input () input is character type.
6, see Help function assistance ():

Copy Code code as follows:

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

ID (...)
ID (object)-> integer

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

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

Second, function
1, function definition and its invocation:

Copy Code code as follows:

#define FUNCTION:ADD (function description)
def add (x,y): #函数头部, note colon, formal 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 as follows:
1, the form participates in the use of the actual parameter, 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 3,python return value allows multiple. Such as:

Copy 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 '

Run Result:

Copy 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 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, which is not contradictory to "do not require predefined data types"
Print Y
def main ():
F1 ()
F2 ()
#f3 () #变量报错
Main ()
print ' end2! '

3, modify the value of the global variable:

Copy 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

Run Result:

Copy Code code as follows:

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

Expressions and Branching statements
1, expression:
is a combination of numbers, operators, digit group notation brackets, free variables and constraint variables, and so on, by means of a meaningful permutation that can be computed numerically. Indicates that there are usually two parts of operands and operators.
Category: arithmetic expressions; relational expressions, logical expressions (And/or/not)
2,IF Branch Statement:
1) Form one: (if <condition>:)

Copy Code code as follows:

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

2) Form two: (if <condition>: Else (if <condition>:))

Copy Code code as follows:

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

Run Result:

Copy Code code as follows:

>>>
Please input your Sex:male
man!

3 Form III: (If <condition>: Elif <condition>: Else)) (This is the form of Python and C)

Copy 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! '

Run Result:

Copy Code code as follows:

>>>
Please input your score:90
Excellent!

Note: Python does not have a switch statement.

Four, circular statement:
Background: In the program design, often encountered a number of statements are repeatedly executed, such code is very long and inefficient, very intuitive, then should consider using the loop body to achieve.
1,while statement: and C in the expression of a difference, C has while and do......while form; Python under: While and while......else ... Form
1) While form:

Copy Code code as follows:

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

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

Copy Code code as follows:

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

Note: If the while non-normal state ends (that is, the loop condition does not end), the Else statement does not execute. As follows:

Copy 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!"

Run Result:

Copy Code code as follows:

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

Add:
Continue statement: In the while loop body appears, the statement under this circular continue is not executed, directly into the next loop.

Copy 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!"

Run Result:

Copy 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 (branches and loops) 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.