|
14 | 14 | <section xml:id="simple-if"> |
15 | 15 | <title>Simple if</title> |
16 | 16 |
|
17 | | - <pre>if condition: statement1 statement2 ...</pre> |
18 | 17 | <p> |
19 | | - In Java this same pattern is simply written as: |
| 18 | + In Python the simple if statement is written as: |
20 | 19 | </p> |
21 | 20 |
|
22 | | - <pre>if (condition) { statement1 statement2 ... }</pre> |
| 21 | + <program interactive="activecode" language="python"> |
| 22 | + <code> |
| 23 | +score = 95 |
| 24 | +if score >= 90: |
| 25 | + print("Excellent work!") |
| 26 | + </code> |
| 27 | + </program> |
| 28 | + <p> |
| 29 | + In Java, this same pattern requires two changes: the condition must be in parentheses <code>()</code>, and the code block must be enclosed in curly braces <code>{}</code>. |
| 30 | + </p> |
| 31 | + <program interactive="activecode" language="java"> |
| 32 | + <code> |
| 33 | + public class SimpleIfExample { |
| 34 | + public static void main(String[] args) { |
| 35 | + int score = 70; |
| 36 | + if (score <= 70) { |
| 37 | + System.out.println("Needs work!"); |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + </code> |
| 42 | + </program> |
23 | 43 | <p> |
24 | 44 | Once again you can see that in Java the curly braces define a block rather than indentation. |
25 | | - In Java the parenthesis around the condition are required because if is technically a function that evaluates to True or False. |
| 45 | + In Java the parenthesis around the condition are required because it is technically a function that evaluates to True or False. |
26 | 46 | </p> |
27 | 47 | </section> |
28 | 48 |
|
29 | 49 | <section xml:id="if-else"> |
30 | 50 | <title>if else</title> |
31 | 51 |
|
32 | | - <pre>if condition: statement1 statement2 ... else: statement1 statement2 ...</pre> |
33 | | - <p> |
34 | | - In Java this is written as: |
35 | | - </p> |
36 | | - |
37 | | - <pre>if (condition) { statement1 statement2 ... } else { statement1 statement2 ... }</pre> |
| 52 | + <p>The Java equivalent follows the same syntactical rules as before.</p> |
| 53 | + <program interactive="activecode" language="python"> |
| 54 | + <code> |
| 55 | + age = 16 |
| 56 | + if age >= 18: |
| 57 | + print("You can vote.") |
| 58 | + else: |
| 59 | + print("You are not yet eligible to vote.") |
| 60 | + </code> |
| 61 | + </program> |
| 62 | + |
| 63 | + <program language="java"> |
| 64 | + <code> |
| 65 | + public class IfElseExample { |
| 66 | + public static void main(String[] args) { |
| 67 | + int age = 16; |
| 68 | + if (age >= 18) { |
| 69 | + System.out.println("You can vote."); |
| 70 | + } else { |
| 71 | + System.out.println("You are not yet eligible to vote."); |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + </code> |
| 76 | + </program> |
38 | 77 | </section> |
39 | 78 |
|
40 | 79 | <section xml:id="elif"> |
|
0 commit comments