Summary
In this lesson, you learned that:
if condition then … endruns its block only if the condition is true.thenandenddecide what belongs to the block; the indentation by 4 spaces shows it to people.elseadds a branch for when the condition is false, andelseif(one word) adds more branches with conditions of their own. Only the first true branch runs, so the order matters. Oneendcloses the whole statement;else ifwould need another one.- Comparison operators compare two values:
==,~=(not!=),<,>,<=and>=.=assigns, while==compares. Texts are equal only if they match exactly. A number is never equal to a text, and comparing them with<or>is an error. - A variable created with
localinside a block exists only until the end of the block. Create it before theif, and change it in the branches. and,orandnotcombine conditions. Each part must be a whole comparison, andnotapplies only to the value right after it. Parentheses group conditions.- Only
falseandnilcount as false.0and""count as true.if x thenasks whetherxhas a value (isn'tnil). x or defaultgives a default value instead ofnil.condition and a or bchooses between two values, as long asaisn'tfalseornil.- An
ifcan be nested in anotherif; eachendcloses the nearest openif. - A range needs two comparisons:
t >= 10 and t <= 25.10 <= t <= 25is an error. In anelseifchain, each branch can rely on the conditions above it being false.
In the next lesson, on loops, you'll learn to make a program repeat code: for example, to go through all the days of a season.
Instructions
Practice: Hugo the trader pays 10 coins for a pumpkin lighter than 4 kg, 20 coins for one from 4 to 8 kg, and 35 coins for a heavier one. In place of the comment, write an if statement with elseif and else that sets price. With 9 kg, the program prints:
Pumpkin: 9 kg
Price: 35 coinsA pumpkin that isn't ripe is worth only half. Below your if statement, add another one that halves the price with price // 2 when the pumpkin isn't ripe (use not). Then add Hugo's bonus to the price. bonus may be nil, so use or to count a missing bonus as 0, and put that part in parentheses: (bonus or 0). The program still prints Price: 35 coins.
Try another pumpkin: change weight to 8, isRipe to false and bonus to 3. The program prints:
Pumpkin: 8 kg
Price: 13 coinsIf it prints another price, check the boundaries: a pumpkin of 8 kg is still medium.
Start programming for free
10/10