How To

How to Use Conditional Statement and Loops in Python

Member
By Amanda Morin
User-Submitted Article
(3 Ratings)

Conditional statements and loops are the basic flow control of any Python program. Once you have mastered the construction of blocks of code in Python, you can begin to create conditional statements and loops and build a computer program. The Python language relies on "if" statements to create conditional statements.

Difficulty: Moderate
Instructions
  1. Step 1

    Write a conditional statement. In a conditional statement actions and/or computations are performed based on whether your specified condition evaluates to true or false. A Python conditional use the "if" keyword and is followed by the boolean expression (the specified condition).

  2. Step 2

    Use the ":" character at the end of the condition to delimit a new block. For example: "if celsius > 20:"

  3. Step 3

    Write the statements inside the block. Use indentation to define which statements are inside the block, remembering that Python uses levels of indentation to delineate code blocks. Thus any statements in the block must be indented more than your "if" statement and at the same level of indentation as each other.

    "if celsuis > 20:
    print "It's getting warm out there!"
    print "I don't think you need your jacket anymore.""

  4. Step 4

    Write "elseif" clauses. An "if" statement evaluates to true--that is, if, and only if, the condition is met then the statement block is executed. Should the condition not evaluate to true your program will continue to the next block of code. "Elseif" statements give the program an opportunity to define what to do when the condition doesn't evaluate to true but evaluates to another specific condition. For example:
    "if celsius > 20:
    print "It's getting warm out there!"
    print "I don't think you need your jacket anymore."
    elseif celsius < 10:
    print "It's still cold out!"
    print "Put your jacket on.""

  5. Step 5

    Conclude with an "else" statement if needed. Should none of the defined conditions be met, then the program will perform the action defined by the "else" statement. An else statement give the program an opportunity to define what to do when the condition doesn't evaluate to true.

    "else:
    print "It's starting to get cold out there."
    print "Think about grabbing a jacket before you go out.""

Post a Comment

Post a Comment
  • Have you done this? Click here to let us know.
I Did This

Related Ads

Computers
Alexia Petrakos,

Meet Alexia Petrakos eHow's Computers Expert.

Get Free Computers Newsletters

Copyright © 1999-2009 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy.   en-US

eHow Computers
eHow_eHow Technology and Electronics