Python Study Notes (4): control flow

Source: Internet
Author: User

Python control statements include if, while, for, break, and continue.

1. If statement

The following is an example of a guess digital game:

# Filename: if.pynumber = 10guess = int(input("Enter a integer:"))if guess == number:    print("Congratulations, you guessed it.")elif guess < number:    print("No, it is a little higher than that")else:    print("No, it is a little lower than that")

Note that the if statement ends with a colon (:), and all control statements end with a colon. Python does not have a switch statement. You can use if... Elif... else to perform the same function.

2. While statement

You may find that you have to start a number game before you can guess it. You can use the while statement to control it until you guess it.

# Filename: while.pynumber = 10running = Truewhile running:    guess = int(input("Enter a integer:"))    if guess == number:        print("Congratulations, you guessed it.")        running = False    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 game is over.")

In fact, the else relative to the while statement is redundant, which is the same as placing its statement directly behind the while statement block.

3. For statement
# Filename: for.pyfor i in range(1, 5):    print(i)else:    print("The for loop is over.")

Output result:

1

2

3

4

The for loop is over.

4. Break statement
# Filename: break.pywhile True:    s = input("Enter something:")    if s == "quit":        break    print("Length of the string is", len(s))print("Done")
5. Continue statement
# Filename: continue.pywhile True:    s = input("Enter something:")    if s == "quit":        break    if len(s) < 3:        continue    print("Input is of sufficient length")

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.