Python learning notes (2) basic syntax

Source: Internet
Author: User

It is not particularly difficult to learn the basic syntax of Python. with the basic knowledge of C, it is easier to understand. The main content of this article is the basic Python syntax. After learning it, you can use it skillfully. (The development environment is still Python2.7, simple to use)
I. Basic Knowledge
1. Data types do not need to be pre-defined (this is a debatable statement, let alone). This is the biggest difference from other languages (such as C, C ++, C #, Delphi, etc)

Copy codeThe Code is as follows:
>>> X = 12
>>> Y = 13
>>> Z = x + y
>>> Print z
25

Note: Although variables do not need to be pre-defined, they must be assigned values when used. Otherwise, an error is returned:

Copy codeThe Code is 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 type () of the variable ():

Copy codeThe Code is as follows:
1 >>> type (x)
2 <type 'int'>

3. view the variable's memory address function id ():

Copy codeThe Code is 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, we can find that the point of the variable is changed, and the address remains unchanged. In other words, the address value of integer 12 remains unchanged, and the point of the variable changes (such as the address of x );
4. Output Function print ():

Copy codeThe Code is as follows:
>>> X = 'day'
>>> Y = 13.4
>>> Print x, type (x)
Day <type 'str'>
>>> Print y, type (y)
13.4 <type 'float'>

Comma operator (,): connects string and numeric data.

Copy codeThe Code is as follows:
>>> Print 'X = ', 12
X = 12

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

Copy codeThe Code is as follows:
>>> X = 12
>>> Y = 13.0004
>>> Z = 'python'
>>> Print "output % d % f % s" % (x, y, s)
Output 12 13.000400 Python

5. Input Function raw_input ():

Copy codeThe Code is as follows:
>>> Raw_input ("input an int :")
Input an int: 12
'12'

Note: raw_input () is of the lag type.
6. view the help function help ():

Copy codeThe Code is as follows:
>>> Help (id)
Help on built-in function id in module _ builtin __:

Id (...)
Id (object)-> integer

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

Note: For Python annotations, #: only single-line annotations are supported. In addition, Python programming has a strict indent format.

Ii. Functions
1. Function Definition and call:

Copy codeThe Code is as follows:
# Define function: add (function description)
Def add (x, y): # function header. Pay attention to the colon, parameter x, and Parameter y.
Z = x + y # function body
Return z # return Value
# Define main function
Def main ():
A = 12
B = 13
C = add (a, B) # function call, real parameters a, B
Print c
Main () # No parameter function call
Print 'end1! '

Note: the similarities and differences between this part and C are as follows:
1. the shape is used in the real parameter usage. The rules are the same, such as no Parameter Function, parameter function, and default parameter.
For example, def add (x, y = 2). The call can be add (3), add (3, 4), add (y = 34, x)
2. The data type must be specified for the form parameter of C, but not for Python.
3. Multiple return values of Python are allowed. For example:

Copy codeThe Code is as follows:
Def test (n1, n2 ):
Print n1,
Print n2
N = n1 + n2
M = n1 * n2
N1-n2 =
E = n1 ** n2
Return n, m, p, e
Print 'entry programme1'
Sum, multi, plus, powl = test () # This is a value assignment method not available in C.
Print 'sum = ', sum
Print 'multi = ', multi
Print 'plus = ', plus
Print 'powl = ', powl
Re = test (2, 10)
Print re # data type: 'tuple'
Print re [0], re [1], re [2], re [3]
Print 'end1! \ N'

Running result:

Copy codeThe Code is 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 codeThe Code is as follows:
Def f1 ():
X = 12 # local variables
Print x
Def f2 ():
Y = 13 # local variables
Print y
Def f3 ():
Print x # error: No variable x is defined, which is not in conflict with "no pre-defined data type is required"
Print y
Def main ():
F1 ()
F2 ()
# F3 () # Variable Error
Main ()
Print 'end2! '

3. Modify the value of the global variable:

Copy codeThe Code is as follows:
Def modifyGlobal ():
Global x # global variable definition
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

Running result:

Copy codeThe Code is as follows:
>>>
Before modified global x = 200
Write x =-1
After modified global x =-1

Iii. Expressions and branch statements
1, expression:
It is a combination of numbers, operators, numeric grouping symbol parentheses, free variables, and constraint variables obtained by meaningful permutation of values. It usually consists of an operand and an operator.
Classification: arithmetic expression, relational expression, logical expression (and/or/not)
2. if branch statement:
1) Form 1: (if <condition> :)

Copy codeThe Code is as follows:
>>> Sex = "male"
>>> If sex = 'male ':
Print 'man! '
# Here there are two return keys
Man!
>>>

2) Form 2: (if <condition>: else (if <condition> :))

Copy codeThe Code is as follows:
Sex = raw_input ('Please input your sex :')
If sex = 'M' or sex = 'male ':
Print 'man! '
Else:
Print 'Woman! '

Running result:

Copy codeThe Code is as follows:
>>>
Please input your sex: male
Man!

3) Form 3: (if <condition>: elif <condition>: else) (this is a form that Python has but C does not have)

Copy codeThe Code is as follows:
Count = int (raw_input ('Please input your score :'))
If count> = 90:
Print 'excellent! '
Elif count> = 80:
Print 'excellent! '
Elif count> = 70:
Print 'qualified! '
Elif count> = 60:
Print 'pass! '
Else:
Print 'failed! '

Running result:

Copy codeThe Code is as follows:
>>>
Please input your score: 90
Excellent!

Note: Python does not have a switch statement.

Iv. Cyclic statements:
Background: when designing a program, some statements are often repeatedly executed. Such code is extremely long, inefficient, and not intuitive. Therefore, we should consider using a loop body for implementation.
1. while statement: It is different from C in expression. c has while and do ...... While format; in Python: while and while ...... Else ...... Form
1) In the while format:

Copy codeThe Code is as follows:
I = 1
While I <5:
Print 'Welcome you! '
I = I + 1

2) while ...... Else ...... Form:

Copy codeThe Code is as follows:
I = 1
While I <5:
Print 'Welcome you! '
I = I + 1
Else:
Print "While over! "# Loop ends normally

Note: If the while statement ends abnormally (that is, it does not end according to the loop condition), The else statement is not executed. As follows:

Copy codeThe Code is as follows:
I = 1
While I <5:
Print 'Welcome you! '
I = I + 1
If I = 2:
Print 'while ...... '
Break
Else:
Print "While over! "

Running result:

Copy codeThe Code is as follows:
1 >>>
2 Welcome you!
3 While ......

Supplement:
Continue statement: When the while LOOP body appears, the statements under this loop continue are not executed and directly enter the next loop.

Copy codeThe Code is 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! "

Running result:

Copy codeThe Code is as follows:
>>>
Welcome you!
While ...... Continue
Welcome you!
While ...... Continue
Welcome you!
While over!

V. Summary:

This article describes how to use Python variables, input and output functions, expressions, basic statements (branches and loops), and other knowledge. through practice, we 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.