The
second form of if statement is alternative execution. Some programmers call
this an if/else statement. In this alternative execution there are two
possibilities and based on condition it determines which one gets executed. The
syntax of the code looks like this:
>>>If x % 2 == 0: … print ‘x is even’ …else: … print ‘x is odd’
If the remainder when x is divided by 2 is 0, then we
know that x is even, and the program displays a message to that effect. So if
the condition is false the second set of statements is executed. Since the
condition must be true or false, exactly one of the alternatives will be
executed. The alternatives are called braches, because they are branches in the
flow of execution. Here is full example of alternative execution:
>>>value = raw_input(“Enter a value: “) Enter a value: 45 >>>x = int(value) >>>if x%2==0: … print ‘x is even’ …else: … print ‘x is odd’ x is odd
Nema komentara:
Objavi komentar