Python Learning (5)

Source: Internet
Author: User
ArticleDirectory
    • 1. If statement:
    • 2. While statement:
    • 3. For Loop:
    • 4. Break statement:
    • 6. Continue statement:
5. Control Flow 1. If statement:

If the if condition is true,ProgramRun the if block. Otherwise, run the else block. Else statements are optional.

For example:

# Filename: If. PY number = 23 guess = int (input ('enter an integer: ') If guess = Number: Print ('Congratulations, you guessed it. ') # new block starts here print (' (but you do not win any prizes !) ') # New block ends hereelif guess <number: Print ('No, it is a little higher than that ') # Another block # You can do whatever you want in a block... else: Print ('No, it is a little lower than that ') # You must have guessed> number to reach here print ('done') # this last statement is always executed, after the if statement is executed

Output:

C: \ Users \ Administrator> Python D: \ Python \ If. py

Enter an integer: 50

No, it is a little lower than that

Done c: \ Users \ Administrator> Python D: \ Python \ If. py

Enter an integer: 22

No, it is a little higher than that

Done c: \ Users \ Administrator> Python D: \ Python \ If. py

Enter an integer: 23

Congratulations, you guessed it.

(But you do not win any prizes !)

Done

Working principle:

In this program, we get the number of guesses from the user, and then check whether the number is the one in our hands. We set the variable number to any integer we want. In this example, It is 23. Then, we use the input () function to obtain the user's guess number. A function is only a reusable program segment.

We provide a string for the built-in input function, which is printed on the screen and waits for the user's input. Once we enter something and press the Enter key, the function returns the input. The input function is a string. We use int to convert the string to an integer and store it in the variable guess. In fact, Int Is a class, but all you need to know about it is that it converts a string into an integer (assuming this string contains a valid integer text ).

Note: In python3, there is no previous version of raw_input () function, which is replaced by input.

Next, we will compare the user's guess with the number we selected. If they are the same, we can print a successful message. Note that we use an indent level to tell which block each statement belongs to in Python. This is why indentation is so important in Python.

Note that the if statement contains a colon at the end, which is used to tell python to follow a statement block.

Then, we will test whether the guess is smaller than our number. If so, we will tell the user that the guess is a little larger. Here we use the Elif clause, which combines two associated if else-If else statements into an IF-Elif-else statement. This makes the program simpler and reduces the number of indentation required.

Both the Elif and else clauses must have a colon at the end of the logical line, followed by a corresponding statement block.

You can also use another if statement in an if block, which is called a nested if statement.

The Elif and else sections are optional. The simplest and most effective if statement is:

 
If true: Print ('Yes, it is true ')

After executing a completeIfStatement andElifAndElseAfter the clause, it movesIfThe next statement of the statement block.

Note: Not in PythonSwitchStatement. You can useIf... Elif... elseStatement to do the same job (in some cases, using a dictionary is faster)

2. While statement:

If one condition is true, the while statement allows you to execute one statement repeatedly. A while statement is an example of a loop statement. The while statement has an optional else clause.

For example:

 
# Filename: While. PY number = 23 running = true while running: Guess = int (input ('enter an integer: ') If guess = Number: Print ('Congratulations, you guessed it. ') Running = false # This causes the while loop to stop Elif guess <number: Print ('No, it is a little higher than that. ') else: Print ('No, it is a little lower than that. ') else: Print ('the while loop is over. ') # Do anything else you want to do here print ('done ')

Output:

C: \ Users \ Administrator> Python D: \ Python \ while. py

Enter an integer: 50

No, it is a little lower than that.

Enter an integer: 22

No, it is a little higher than that.

Enter an integer: 23

Congratulations, you guessed it.

The while loop is over.

Done

In this program, we still use the guessing game as an example, but the advantage of this example is that users can continuously guess the number, until he guessed it right-so that he does not need to repeat the program for each guess as in the previous example. This example properly describes the use of the while statement.

We move the input and if statements to the while loop, and set the running variable to true before the while loop starts. First, check whether the variable running is true, and then execute the while-block. After this program is executed, check the condition again. In this example, the condition is the running variable. If it is true, we will execute the while-block again. Otherwise, we will continue to execute the optional else-block and then execute the next statement.

When the while loop condition changes to false, the else block is executed-or even when the condition is verified for the first time. If a while loop has an else clause, it will always be executed unless your while loop will always go down and will not end!

Note: Here (there is no break in the loop), The else block is actually redundant, because you can put the statements in the same block (the same as while, after the while statement, you can achieve the same effect.

True and false are called boolean types. They can be equivalent to 1 and 0 respectively. When checking important conditions, Boolean types are very important. They are not true values of 1.

3. For Loop:

For... In is another loop statement that recursively uses each item in the queue on a series of objects.

For example:

 
# Filename: For. py for I in range (1, 5): Print (I) else: Print ('the for loop is over ')

Output:

C: \ Users \ Administrator> Python D: \ Python \ for. py

1

2

3

4

The for loop is over

Working principle:

In this program, we print the number of a sequence. We use the built-in range Function to generate the sequence of this number.

All we do is provide two numbers, and range returns the number of a sequence. This sequence starts from the first number to the second number. For example, range (1, 5) gives the sequence [1, 2, 3, 4]. By default, the step of range is 1. If we provide the third number for range, it will be the step size. For example, range (, 2) provides [].

Note:

    • Range is extended up to the second number, that is, it does not contain the second number.
    • For Loop recursion in this range -- for I in range () is equivalent to for I in [1, 2, 3, 4], this is like assigning each number (or object) in the sequence to I, one at a time, and then executing the program block with each I value. In this example, we only print the I value.
    • The else part is optional. If else is included, it is always executed once after the for loop ends, unless a break statement is encountered.
    • The for... in loop applies to any sequence. Here we use a list of numbers generated by the built-in range function, but in a broad sense, we can use a sequence of any types of objects!
    • PythonForA loop is fundamentally different from a C/C ++ForLoop. C # the programmer will notice the pythonForLoop in C #ForeachThe loop is very similar. Java programmers will notice thatFor (int I: intarray)Similar. In C/C ++, if you want to writeFor (INT I = 0; I <5; I ++)In python, you can writeFor I in range (0, 5). You will notice that python'sForThe cycle is simpler, clearer, and error-free.
4. Break statement:

The break statement is used to terminate a loop statement, that is, even if the loop condition is not called false or the sequence is not completely recursive, the execution of the loop statement is stopped.

Note: If you terminate a for or while loop, no corresponding loop else block will be executed.

For example:

# Filename: Break. PY while true: S = input ('enter something: ') If S = 'quit': Break print ('length of the string is', Len (s )) print ('done ')

Output:

C: \ Users \ Administrator> Python D: \ Python \ break. py

Enter something: programming is fun

Length of the string is 18

Enter something: when the work is done

Length of the string is 21

Enter something: If you wanna make your work also fun:

Length of the string is 37

Enter something: Use python!

Length of the string is 12

Enter something: Quit

Done

Working principle:

In this program, we repeatedly obtain the user input, and then print the length of each input location. We provide a special condition to stop the program, that is, to check whether the user input is 'quit '. Stop the program by terminating the loop to the end of the program.

The length of the input string is obtained through the built-in Len function.

The break statement can also be used in the for loop.

6. Continue statement:

The continue statement is used to tell python to skip the remaining statements in the current loop block and continue the next loop.

For example:

 
# Filename: continue. PY while true: S = input ('enter something: ') If S = 'quit': break if Len (s) <3: Print ('too small ') continue print ('input is of sufficient length') # Do other kinds of processing here...

Output:

C: \ Users \ Administrator> Python D: \ Python \ continue. py

Enter something:

Too small

Enter something: 12

Too small

Enter something: ABC

Input is of sufficient length

Enter something: Quit

Working principle:

In this program, we get input from users, but we only process them when they have at least three characters long. Therefore, we use the built-inLenFunction to obtain the length. If the length is less than 3, we useContinueThe statement ignores the remaining statements in the block. Otherwise, the remaining statements in this loop will be executed, and we can do whatever we want here.

Note:ContinueStatementForThe cycle is also valid.

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.