Conditional statements are ones that are executed only if some condition is true. Here's an example: x = 5 if x<6: print 'x is less than 6' if <condition>: <statement> An else clause says what to do if the 'if' condition is false, e.g., if x<6: print 'less than 6' else: print 'more or equal to 6' if x<6: print 'less than 6' elif x<10: print 'between 6 and 10' else: print 'ten or bigger' Comparison and Logical OperatorsHere are examples of the comparison operators that you can use in conditionals:x < 3 x > 3 x == 3 x != 3 x <= 3 x >= 3 Note that == is used for equality comparison as opposed to = (the assignment operator). This causes a lot of errors even for experienced programmers. != means not equal. You can also use the logical operators and, or, and not, to create more complex conditions, e.g., if (x<3 and y != 7): Statement BlocksOften, in a conditional statement, you want more than one thing to occur. Programming languages allow you to define a statement block, which is one or more statements that are grouped together. In many languages, such as C, C++, and Java, curly braces are used to denote statement blocks:if <condition> { <statement> <statement> ... } In such languages, indentation is ignored by the compiler. Python is different. It uses indentation to define where a block begins and ends and doesn't use curly brackets. Tabs are used to indent:if <condition> :
<statement>
<statement> ... Can you figure out the value of x following the following snippet: x=5 if x<4: x=x+1 x=x+1 What if x began as 3? |