Python Learning Path--03 flow control statement

Source: Internet
Author: User
Tags class operator logical operators switch case

Directory

    • An expression
    • Process Control Statements
      • Conditional control Statements
      • Loop control Statements
An expression

An expression is a sequence of operators (operator) and operands (operand). is one of the most basic concepts in programming languages

In short, the expression in Python is a line-by-row statement

>>> 1+1112>>> a = [1,2,3]>>> 1+1+1*24>>> a = 1+2*3>>> a = 1>>> b = 2>>> c = a and b or 0>>> c = int(‘1‘) + 2

The line input in the example is called an expression. When it comes to expressions, it is not a matter of prioritization between expressions. Python has different class operator precedence as shown in.

Attention:

    • () the highest priority , which can be used () to validate and modify the order of execution
    • There are also priority issues in the same-level operators. As in logical operators not > and >or
    • The order of execution in the same class is executed from left to right, which is left associative . However, when an assignment occurs = , it becomes the right combination , that is, whether = it is the current first priority or not, the = right part of the calculation is completed first
>>> a or b and c1>>> not a or b + 2 == cFalse>>> (not a) or ((b + 2) == c)False>>> b = a is c
Process Control Statements
    • Conditional control statements--selectivity issues
    • Circular control Statement--a basic idea of solving problems
Conditional control Statements

That is, the if else statement. Python is used in the form of

if 逻辑判断 :    deal with things    ...else :    deal with other things    ...

Python specification broken read:

  • Python default each line is a statement, different from C, Java, etc. must be in ; the end of the way, the statement at the end of the Python ; is optional
  • Python does not rely on {} identifying blocks of code, but relies on indentation to identify blocks of code, and therefore Python code cannot be compressed and confused. indentation requirements are 4 spaces as a benchmark, notice the setting of the tab step amount in tools such as the IDE

Conditional judgment is the most commonly used scenario to detect the user login condition judgment, the following simple simulation. input() is a function that can get the user input on the console, the function is said separately

account = ‘Daniel Meng‘password = ‘123456‘print(‘please input account‘)user_account = input()print(‘please input password‘)user_password = input()if account == user_account and password == user_password :    print(‘success‘)else :    print(‘fail‘)
PS E:\Python> python .\c3.pyplease input accountmengplease input password123failPS E:\Python> python .\c3.pyplease input accountDaniel Mengplease input password123456success

Python specification broken read:

  • Python is case-sensitive, Var and var are different
  • Python does not have a constant mechanism, and all variables that wish to represent constants should be all capitalized, such as account
  • The name of the variable in Python if it is a combination of words through the _ connection, different from the hump naming law, etc.
  • Python projects usually have a lot of .py files, a python file is called a module, each module should have a package at the top of the ``` ``` part, to explain the meaning and role of the current module
  • Do not leave spaces in Python before identifiers
  • Each python file should leave a blank line
  • Variables should be placed in functions or classes, and variables exposed directly to the module are generally understood as constants
  • In order to improve readability, multivariate operators such as = the left and right should be blank one grid
‘‘‘    if-else条件语句的使用和规范‘‘‘ACCOUNT = ‘Daniel Meng‘PASSWORD = ‘123456‘print(‘please input account‘)USER_ACCOUNT = input()print(‘please input password‘)USER_PASSWORD = input()if ACCOUNT == USER_ACCOUNT and PASSWORD == USER_PASSWORD :    print(‘success‘)else :    print(‘fail‘)

Control statements can be used independently or nested

if condition:    if expression:        passelse:    if condition:        pass    else:        passif expression:    passif expression:    pass

Here is the concept of the code block brought by indentation. Code for the same indent level is in the same code block, at the same level

# 代码块if expression:    code1        code11        code11            code22            code22                code33                code33    code2    code3else:    code1    code2    code3

When you encounter multi-conditional judgments, you can use the elif syntax, which is else if shorthand. else and elif neither can be seen alone .

a = input()a = int(a)if a == 1:    print(‘apple‘)elif a == 2:    print(‘orange‘)elif a == 3:    print(‘banana‘)else:    print(‘shopping‘)

Note that because Python is a weakly typed language, input() function unification is captured as a string type, and then you need to convert the data to the type you want yourself.

There is no syntax in C,java in Python switch case . Python can be replaced with the form described above if... elif... elif... else . Further official advice can also be used in the form of a dictionary to achieve switch the function of the statement

def function_1(...):    ...functions = {‘a‘: function_1,             ‘b‘: function_2,             ‘c‘: self.method_1, ...}func = functions[value]func()
Loop control Statements

Include while and for two types of loops. First, the while loop.

while condition:    #循环体    do your things    ...orther statements

Looping statements are prone to the error of a dead loop. there must be a statement in the loop body that can affect the cyclic condition.

counter = 0while counter <= 10:    # 代码块    counter += 1    print(‘I am While ‘ + str(counter))

Whether or not Python while can be for paired else to indicate what to do after the loop condition has ended

while condition:    do your things    ...else:    pass

passRefers to an empty operation

While loops are used more recursively, and for loops are used to iterate over sequences, collections, or dictionaries. It can also be said that while many are used for the number of cycles, for the number of cycles to determine the occasion.

for target_list in expression_list:    do your things    ...

The loop format is given above for . It can also be combined with else operation

for target_list in expression_list:    passelse:    pass

loop control statements can be nested using

a = [[‘apple‘,‘orange‘,‘banana‘,‘grape‘],(1,2,3)]for x in a:    for y in x:        print(y,end=‘ ‘)else:    print(‘fruit is gone‘)
PS E:\Python\seven> python .\c2.pyapple orange banana grape 1 2 3 fruit is gone

elsePart will be executed after traversing, or after the for loop is completed.

print()The second parameter can be used in a small trick method end to control the output format of the result, by defaultend = ‘\n‘

In the loop, sometimes special handling of certain situations, such as critical/error exits, ignoring certain values, etc. is often required. This will then be used break and continue manipulated.

breakThe inner loop is terminated, and the part is skipped if the terminated layer loops with a else portion else . continueSkip the current nth cycle and proceed directly to the first n+1 cycle

a = [[‘apple‘,‘orange‘,‘banana‘,‘grape‘],(1,2,3)]for x in a:    for y in x:        if y == ‘banana‘:            break        elif y == 2:            continue        print(y)    else:        print(‘Done‘)
PS E:\Python\seven> python .\c2.pyappleorange13Done

Note In the example, because the break program does not output the banana, grape, and else sections. Because the continue program skipped 2, the rest of the output is normal.

If there are other language backgrounds such as C, Java, and so on, it's for more like for each . What if this is the classic For,python that specifies the number of cycles ?

for(int i = 0; i < n; i++){    do something}

For this, Python uses the range(start,end[,step]) function, which can accept three parameters, which means to step get a range of sequences in steps, the [start,end) step is optional, the default is 1

for x in range(0,10):    print(x, end = ‘ | ‘)print()for x in range(0,10,2):    print(x, end = ‘ | ‘)print()for x in range(10,0,-2):    print(x, end = ‘ | ‘)
PS E:\Python\seven> python .\c3.py0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |0 | 2 | 4 | 6 | 8 |10 | 8 | 6 | 4 | 2 |

Python Learning Path--03 flow control statement

Related Article

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.