[Python] Getting Started tutorial (3): control flow in Python

Source: Internet
Author: User

Like C ++/Java, there are three control flow statements in Python: if, for, and while.

If statement
The IF statement is used to test a condition. If the condition is true, we run a statement (called the IF-block). Otherwise, we will process another statement (called the else-block ). Else clauses are optional.
Use the if statement

Example 1 use the if statement

#!/usr/bin/python# Filename: if.py number = 23guess = 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 guess > number to reach hereprint('Done')# This last statement is always executed, after the if statement is executed 

Output
$ Python if. py
Enter an integer: 50
No, it is a little lower than that
Done
$ Python if. py
Enter an integer: 22
No, it is a little higher than that
Done
$ Python if. py
Enter an integer: 23
Congratulations, you guessed it.
(But you do not win any prizes !)

Done



How it works

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. In the next chapter, we will learn more about functions.

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

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. We hope to adhere to the "One tab per indentation layer" rule.

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 (including correct indentation, of course ).

You can also use another if statement in an if block, and so on -- this is called a nested if statement.

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

If true:
Print 'Yes, it is true'

After Python executes a complete if statement and the Elif and else clauses associated with it, it moves to the next statement in the IF statement block. In this example, the Statement block is the main block. The program runs from the main block, and the next statement is the print 'done' statement. After that, Python sees the end of the program and simply ends the running.

Although this is a very simple program, I have pointed out a lot of things you should pay attention to in this simple program. All of these are very straightforward (especially for users with C/C ++ backgrounds ). They will attract your attention at the beginning, but you will be familiar with them and "natural" in the future ".

Comments to C/C ++ programmers

There is no switch statement in Python. You can use the IF... Elif... else statement to do the same job (in some cases, it is faster to use the dictionary .)


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.

Use the while statement
Example 2 use the while statement

#!/usr/bin/python# Filename: while.pynumber = 23running = Truewhile 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 hereprint('Done')


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

How it works
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 raw_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 -- this may even be the first time the condition is verified. 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!

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

The else block is actually redundant, because you can put the statements in the same block (the same as while) after the while statement, so that the same effect can be achieved.

Comments to C/C ++ programmers
Remember, you can use an else clause in the while loop.


For Loop
For... In is another loop statement that recursively uses each item in the queue on a series of objects. We will learn the sequence in more detail in subsequent chapters.

Use the for statement
Example 3 use the for statement

#! /Usr/bin/Python # filename:. pyfor I in range (1, 10, 2): # the third digit is the step size print (I) else: Print ('the for loop is over ')


Output
$ Python for. py
1
2
3
4
The for loop is over

How it works
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 []. Remember, 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.

Remember, 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.

Remember, 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! We will explore this point in detail in later chapters.

Comments to C/C ++/Java/C # programmers
The for loop of python is fundamentally different from the for loop of C/C ++. C # programmers will notice that the For Loop in python is very similar to the foreach loop in C. Java programmers will notice that it is similar to for (int I: intarray) in Java 1.5.
In C/C ++, if you want to write for (INT I = 0; I <5; I ++), use python, you can write for I in range (0, 5 ). You will notice that the python for loop is simpler, clearer, and error-free.

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.

An important note is that if you terminate a for or while loop, no corresponding loop else block will be executed.
Use the break statement

Example 4 use the break statement

#!/usr/bin/python# Filename: break.pywhile True:    s = input('Enter something : ')    if s == 'quit':        break    print('Length of the string is', len(s))print('Done')


Output

$ 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
How it works

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.

Remember, the break statement can also be used in the for loop.
Python poems of G2

Here I entered a small poem I wrote, called the python poem G2:

Programming is fun
When the work is done
If you wanna make your work also fun:
Use python!



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.

Use the continue statement
Example 5 use the continue statement

#!/usr/bin/python# Filename: continue.pywhile True:    s = input('Enter something : ')    if s == 'quit':        break    if len(s) < 3:        continue    print('Input is of sufficient length')    # Do other kinds of processing here... 

Output
$ Python continue. py
Enter something:
Enter something: 12
Enter something: ABC
Input is of sufficient length
Enter something: Quit

How it works
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-in Len function to obtain the length. If the length is less than 3, we will use the continue statement to ignore 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 that the continue statement is also valid for the for loop.

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.