Python study notes (ii) basic syntax

  • 2020-04-02 13:44:54
  • OfStack

Learning Python, the basic syntax is not particularly difficult, with the basic knowledge of C, easy to understand. The main content of this article is the basic Python syntax, after learning, can skillfully use it. (the development environment is still Python2.7, simple to use)
One, basic knowledge
1. There is no need to pre-define the data type (this is debtable, let's just say this), which is the biggest difference from other languages (such as C,C++,C#, Delphi, etc.).


 >>> x=12
 >>> y=13
 >>> z=x+y
 >>> print z
 25

Note: although variables do not need to be defined in advance, they must be assigned when they are used, otherwise an error is reported:


 >>> 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:


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

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


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

It can be found from the above results that the direction of the variable changes while the address remains unchanged. In other words, the address value of the integer 12 remains unchanged, and the direction of the variable changes (such as the address change of x).
4. Output function print() :


 >>> x='day'
 >>> y=13.4
 >>> print x,type(x)
 day <type 'str'>
 >>> print y,type(y)
 13.4 <type 'float'>

Comma operator (,) : concatenates strings and numeric data.


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

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


 >>> 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():


 >>> raw_input("input an int:")
 input an int:12
 '12'

Note: raw_input() is typed in character type.
6. See the help function help():


>>> 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 among
    simultaneously existing objects. (Hint: it's the object's memory address.)

Note: Python comments, # : only supports single-line comments; In addition, Python programming has a strict indentation format.

Second, the function
1. Function definition and its call:


#define function:add  (function description) 
def add(x,y):  # The head of the function, notice the colon, the parameter x,y
    z=x+y           # The body of the function 
    return z        # The return value 
#define main function
def main():
    a=12
    b=13
    c=add(a,b)   # Function calls, arguments a,b
    print c
main()             # Call a function without arguments 
print 'End1!'

Note: the similarities and differences between this part and the existence of C are as follows:
1. The usage of the form participating arguments, the non-argument function, the argument function, the default parameter and so on are consistent.
If def add(x,y=2), the call can be add(3) or add(3,4), add(y=34, x)
2, the parameters of C need to specify the data type, but Python does not.
3. Python returns multiple values. Such as:


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)   # This is a C An assignment that a language does not have 
print 'sum=',sum
print 'multi=',multi
print 'plus=',plus
print 'powl=',powl
re=test(2,10)
print re                                # The data type is: 'tuple'
print re[0],re[1],re[2],re[3]
print 'End1!n'

Operation results:


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:


def f1():
    x=12     # A local variable 
    print x
def f2():
    y=13      # A local variable 
    print y
def f3():
    print x       # Error: no variables were defined x , which is not inconsistent with "no predefined data type. 
    print y
def main():
    f1()
    f2()
    #f3()# Variable error   
main()
print 'End2!'

3. Modify the value of the global variable:


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

Operation results:


>>>
 before modified global x= 200
 write x =-1
 after modified global x= -1

Expressions and branch statements
1. Expression:
          It is a combination of Numbers, operators, number grouping symbol brackets, free variables and constraint variables, etc. in a meaningful arrangement method to obtain values. A representation usually has two parts: an operand and an operator.
          Classification: arithmetic expression; Relational expression, logical expression (and/or/not)
2. If branch statement:
1) form 1 :(if < condition > :)


 >>> sex="male"
 >>> if sex=='male':
  print 'Man!'
 # There are two enter keys 
 Man!
 >>> 

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


 sex=raw_input('Please input your sex:')
 if sex=='m' or sex=='male':
  print 'Man!'
 else:
     print 'Woman!'

Operation results:


 >>>
 Please input your sex:male
 Man!

Form three: if < condition > : elif < condition > : else)) (this is a form that Python has but C doesn't)


count=int(raw_input('Please input your score:'))
if count>=90:
   print' good !'
elif count>=80:
    print ' good !'
elif count>=70:
    print ' qualified !'
elif count>=60:
    print ' Pass the !'
else:
    print ' Don't pass the !'

Operation results:


 >>>
 Please input your score:90
  good !

Note: Python does not have a switch statement.

Iv. Circular statement:
            Background: in the process of programming, it is common to encounter some statements that are repeatedly executed, such code is extremely long, inefficient, and not intuitive, so you should consider using the loop body to achieve.
  1, while statement: different from C in expression, C has while and do... While the form; Python: while and while... The else... In the form of
  1) while form:


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

2) while... The else... Form:


 i=1
 while i<5:
     print 'Welcome you!'
     i=i+1
 else:
     print "While over!"  # End of cycle 

Note: if the while abnormal state ends (that is, the loop condition does not end), the else statement does not execute. As follows:


i=1
while i<5:
    print 'Welcome you!'
    i=i+1
    if i==2:
        print 'While ... '
        break
else:
    print "While over!"

Operation results:


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

Supplement:
Continue statement: when it appears in the body of the while loop, the statement under the loop continue is not executed and goes directly to the next loop.


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 results:


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

Five, summary:

          This article introduces the use of Python's variables, input and output functions, expressions, basic statements (branches and loops), and so on.


Related articles: