Conditional Executions

So far the program examples where short and straightforward. In order to change the behavior of the program and the ability to check the conditions we got to use conditional statements. The simplest form is the if statement:
>>>number = raw_input(“Enter a value: “ )
Enter a value: 50
>>> x = int(number)
>>> if x > 0:
…        print ‘x is positive’
x is positive

The Boolean expression after the if statement is called the conditions. We end the if statement with a colon character (:) and the line(s) after the if statement are indented.
If the logical condition is true, then the indented statement gets executed. If the logical condition is false, the indented statement is skipped. if statements have the same structure as function definitions or for loops. The statement consists of a header line that ends with the colon character (:) followed by an indented block. Statements like this are called compound statements because they stretch across more than one line.

Working with conditional execution.

When you run python from cmd (Command Prompt) in MS Windows or Terminal from any Linux distribution be very careful when creating conditional execution.
If we look at our previous example after typing “if x > 0:” and pressing Enter or Return button on your keyboard the Python will create next line starting with … This three dots indicate you are in the middle of a block of statements Then you have to press at least one space (four is preferable) on your keyboard in order to continue creating the body of conditional execution term. If you don’t do that the Python will throw you out from conditional execution term and will report an IndentationError. The example is given below.
>>> x = 50 
>>> if x > 0:
…print ‘x is positive’ 
 File “”, line 2
      print ‘x is positive’
             ^
IndentationError: Expected an indented block 
Spyder and other GUI programs for Python programming do this indentation automatically after you press Enter or Return button on your keyboard.



There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven’t written yet). In that case, you can use the pass statement, which does nothing.

Nema komentara:

Objavi komentar