Introduction to Python Basics Lesson 11--Conditions, Loops, and Other Statements

    1 Introduction

    Conditions, loops and other control statements that we are familiar with are often used in the C language. We sometimes nest several loops and conditions to meet our needs. In the Python language, there is no doubt that we will When these useful methods or statements are used, will they be used in the same way as in the C language? What can we do with it? Below we will introduce some of these statements.

    2. Conditions and conditional statements

    In the previous chapters, we have described that the statements in the program are executed sequentially one by one. The conditional and conditional statements will introduce the method for the program to choose whether to execute the block of statements.

  • Conditional execution and if statements
#coding:utf-8
name=raw_input('What is your name: ')
if name.endswith('Yang'):
    print 'Hello.Mr.Yang'
/usr/local/bin/python2.7 /Users/yangjiayuan/PycharmProjects/day/day11/use_of_if.py
What is your name: Yang
Hello.Mr.Yang

Process finished with exit code 0
/usr/local/bin/python2.7 /Users/yangjiayuan/PycharmProjects/day/day11/use_of_if.py
What is your name: Sun
You input the wrong name

Process finished with exit code 0

    Analyze the above program, we simply wrote a judgment program, the user enters his name, we make a judgment on the name, if the name is the same as our conditional setting, we give a greeting statement. If the input is not the same as what we set, then we also give a prompt, you can run the program again and enter again. Such simple judgments can be used in simple user perception.

    Let's take a look at the syntax of if: after the statement is entered, it must be followed by a colon, and then enter the statement you want to execute. When the colon in the syntax is missing in the compiler, the compiler will report an error. This is different from the C language. Another point is that when you press the Enter key after entering the colon, there will be a standard indent when the cursor changes to the next line, which can distinguish the attribution very well, and you cannot modify this format at will. Special attention should be paid to multi-level judgments or nesting.

  • elif statement

    If you want to check multiple conditions, you can use elif, which is short for else if, which is a combination of if and else clauses, that is, an else clause with conditions.

#coding:utf-8
name=raw_input('What is your name: ')
if name.endswith('Yang'):
    print 'Hello.Mr.Yang'
elif name.endswith('Zhao'):
    print 'Hello.Mr.Zhao'
else:
    print 'You input the wrong name'

    Does it look neat, here we also use elif, we have to remember it, there is never such a statement in C language. The result of the program running is not shown here, it is basically the same as the above, you can run and see by yourself.

  • statement nesting

    Nesting is actually very simple. What we need to pay attention to is proper indentation to ensure the correctness and rationality of nesting.  

#coding:utf-8
name=raw_input('What is your name: ')
if name.endswith('Yang'):
    if name.startswith('Mr'):
        print 'Hello, Mr.Yang'
    elif name.startswith('Mrs'):
        print 'Hello, Mrs.Yang'
    else:
        print 'Hello, Yang'
else:
    print 'Hello, Stranger'

    Multiple judgments are made here, and the starting character and ending character of the name input by the user are judged, and different processing is performed respectively. The indentation is also very standardized, and each print statement is associated with its corresponding judgment statement. We should also pay attention to these when writing a program, so that our program looks neater and clearer.

    Of course, the description of the if statement is not completed by simply using it in this way. We can contact some of the methods and operations mentioned above to enrich the content of the program, such as what we have talked about: comparison operators, equality operators, in Membership checks, string and sequence comparisons, Boolean operators, etc., can all be added to statements.

  • Affirmation

     Officially, the IF statement has a very useful "close cousin" that works somewhat like the following pseudocode:

if not condition:

    crash program

    Why do we need such code? That's because instead of letting the program crash later, it's better to just let it crash when an error condition occurs. The keyword used in the statement is assert. Let's take a look:

>>> age=10
>>> assert 0<age<100
>>> age=-1
>>> assert 0<age<100
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
>>> age=-1
>>> assert 0<age<100, 'The age must be realistic'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: The age must be realistic

    The second time we deal with it, we add what we want to tell the user after the assert statement, that is, let's explain what the assert is, and just let it crash when the error condition occurs, which saves a lot of money unnecessary trouble. Improve the reliability of our programs.

    3. Loop

    Now that we know how the statement should execute when the condition is true or false, how can we make the program execute multiple times? Do we have to write more times in the program? You should not use this method, Python provides us with loops.

  • while loop

    To avoid unwieldy code, we can do it like this:

#coding:utf-8
x=1

while x<=10:
    print x
    x+=1
/usr/local/bin/python2.7 /Users/yangjiayuan/PycharmProjects/day/day11/use_of_while.py
1
2
3
4
5
6
7
8
9
10

Process finished with exit code 0
  • for loop

    The while statement is flexible. It can be used to execute a block of code if any condition is true. Generally, it is enough, but sometimes it is tailor-made. For example, execute a block of code for each element in the collection.

>>> for i in numbers: print i
...
1
2
3
4
5
6
7
8
9
10

    Because iterating over a range of numbers is common, there is a built-in range function that provides access to: range

>>> range(0,10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    The Range function works like sharding. Remember what I said earlier about including the upper and the lower, the Range function is also like this.

  • loop through dictionary elements

    A simple for loop can iterate over all the keys of the dictionary, as we did with the sequence earlier, which is convenient.

#coding:utf-8
d={'x':'1','y':'2','z':'3'}
for key in d:
    print key, 'corresponds to', d[key]
/usr/local/bin/python2.7 /Users/yangjiayuan/PycharmProjects/day/day11/use_of_for.py
and corresponds to 2
x corresponds to 1
z corresponds to 3

Process finished with exit code 0

    We create a dictionary with three key-value pairs, which we can print out to the screen one by one using a for loop. The upper part is the program content, and the lower part is the code that the program runs. We can also rewrite the above part of the program to the following, and we can also get the same result:

#coding:utf-8
d={'x':'1','y':'2','z':'3'}
for key,value in d.items():
    print key, 'corresponds to' ,value

    The items method returns all the items in the dictionary as a list, in no specific order. The order of dictionary elements is usually undefined, in other words, when iterating, both keys and values ​​in the dictionary are guaranteed to be processed, but the order of processing is uncertain. If order is important, you can keep key values ​​in separate lists. Sort before iteration.

    4. Get out of the loop

    In general, the loop executes until the condition becomes false, or until the sequence runs out of elements. But sometimes it is possible to terminate a loop prematurely, to start a new iteration, or just to end the loop. Common ways to jump out of the loop are as follows:

  • break

The break statement can be used to end the loop:

#coding:utf-8
from math import sqrt
for n in range(99,0,-1):
    root=sqrt(n)
    if root ==int(root):
        print n
        break
    This program will print out the largest square number within 100. When a square number is found, it will stop looping, that is, it will jump out of the loop after finding 81.


  • continue

    Compared to break, the continue statement is rarely used. It will end the current iteration and "jump" to the beginning of the next cycle. It basically means: skip the rest of the loop body, but don't end the loop. It can be handled like this:

#coding:utf-8
for x in seq:
    if condition1: continue
    if condition2: continue
    if condition3: continue
    
    do_something()
    do_somethingelse()
    do_another_thing()
    etc()

    The above code cannot be executed, I just gave the processing mode, and did not put the specific operation into it. It's good that everyone knows this framework, you don't have to worry about specific operations, you can add any operations you want to perform.

    Okay, the knowledge of sentences will be explained here first, and the next chapter will buffer a little bit and talk about some fragmentary but very important little knowledge. It lays the foundation for further abstract concepts we will follow.

Guess you like

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