Concise Python Tutorials

Source: Internet
Author: User
Tags integer in python

Brief introduction

In the program we've seen so far, there's always a series of statements that Python faithfully executes them in their order. What if you want to change the order in which the statement flows are executed? For example, you want the program to make decisions that do different things according to different situations, such as "Good Morning" or "evening" according to time.

As you may have guessed, this is achieved through a control flow statement. There are three kinds of control flow statements--if, for, and while in Python.

If statement

If statements are used to verify a condition, and if the condition is true, we run a statement (called a if-block), otherwise we process another statement (called a else-block). else clauses are optional.

Use the IF statement

Example 6.1 using the IF statement

#!/usr/bin/python
# Filename: if.py
number = 23
guess = int(raw_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 here
elif 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 here
print 'Done'
# This last statement is always executed, after the if statement is executed

(source file: code/if.py)

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

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.