Python basic syntax

Basic Python grammar
This is a little note for beginners to learn python, and it is posted to make the notes more complete.
The following two points are the major differences between the python language and other languages:
1. Forced alignment, python thinks that the same indentation length is a group
2. Expressions are separated by colons

1. Conditional statement if

  1.if <expr1>:<one_line_statement>
  2.if <expr1>:
        <statemnet_block>
  3.if <expr1>:
        <statemnet_block>
    else
        <statemnet_block>
  4.if <expr1>:
        <statemnet_block>
    elif<expr2>:
        <statemnet_block>
    elif<expr...>
        <statemnet_block>
    else
        <statemnet_block>

In fact, it is similar to the conditional statements of many languages ​​such as C, C++, jave, etc., except that python does not use braces to separate code segments, but uses colons and forced alignment to judge code blocks.
2. For loop

  for x in <sequence>:        #可以遍历任何序列的项目,如一个列表或者一个字符串。
    <statement-block>
  else:                       #循环没有被break中断,既正常退出后执行else部分。 else部分可有可无
    <else-block>

例子:
  for letter in 'Python':     # 第一个实例
     print '当前字母 :', letter
输出:
     当前字母 : P
     当前字母 : y
     当前字母 : t
     当前字母 : h
     当前字母 : o
     当前字母 : n

  fruits = ['banana', 'apple',  'mango']
  for fruit in fruits:        # 第二个实例
    print '当前水果 :', fruit
输出:
    当前水果 : banana
    当前水果 : apple
    当前水果 : mango

  dic={"name":"zhangsan","sex":"man","age":15}
  for x in dic :
    print x,":",dic[x]
输出:age : 15
name : zhangsan
sex : man

  for num in range(5,10):       # range返回一个序列的数
      print num
输出:
    5
    6
    7
    8
    9

  sequence = [12, 34, 34, 23, 45, 76]
  for i, j in enumerate(sequence): 
    print i,j
输出:
    0 12
    1 34
    2 34
    3 23
    4 45
    5 76

For loop is different from other languages, python's for loop statement can implement traversal more easily

Three, while loop

  while <expr1>:
    <block>
  else:
    <else-block>        #如果没有break跳出循环,执行else中的内容。
                        #既:expr1为假时。

Fourth, the pass statement The
pass statement does nothing. It is used in situations where there must be some grammatical statement, but the program does
nothing .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325868635&siteId=291194637