Istruzioni Condizionali

I programmi composti da semplici raccolte di istruzioni come nell'esercizio precedente sono piuttosto noiosi, fanno sempre le stesse cose e non regiscono alle codizioni esterne. L'istruzione condizionale permette ad un programma di adattarsi ad una situazione come ad esempio se piove prendi l'ombrello.

La sintassi di [!thelang] è la seguente:

[!java|scala|c]if (condizione) {
    cosaFareSeVero();
    cosaFareInSeguitoSeVero();
}[/!][!python]if condizione:
    cosaFareSeVero()
    cosaFareInSeguitoSeVero()[/!]
cosaFareComunque()[!java|c];[/!]

Se la condizione è vera il codice nel blocco immediatamente sottostante sarà eseguita per poi continuare con il resto del codice. Se la condizione è falsa il codice nel blocco immediatamente sottostante verrà ignorato e l'esecuzione continuerà dopo di esso. Il blocco condizionale può contenere diverse istruzioni, può anche contenere a sua volta altre condizioni con i loro propri blocchi.

In questo esempio le istruzioni cosaFareSeVero() e cosaFareInSeguitoSeVero() saranno eseguite se e solo se la condizione è vera, mentre l'istruzione cosaFareComunque() sarà eseguita sia con la condizione falsa che vera.

In [!thelang], the blocks of code are [!java|scala|c]enclosed between curly brackets: a { sign opens the block, while a } sign closes it. White spaces are not important[/!][!java|c].[/!][!scala], provided that your instructions are still separated with a semi-column or an end of line.[/!] [!java|scala|c]It is still very important to correctly indent your code to keep it readable.[/!] [!python]marked by the indentation: every lines that are a bit shifted to the right with white spaces belong to the block. Quite often, people use 4 spaces for indentation, but it works if you use more or less spaces. Simply, any lines of the block must use the same amount of spaces. The end of Python code blocks are not marked by any specific char. Indenting lines starts a block and unindenting ends it. Do not forget the colon (:) at the end of the if line, python needs it to know that a new block begins. The fact that python relies on indentation to delimit blocks is a very good property for beginners: it will force you to adhere to strict code presentation standards.[/!] It is very easy to get lost in your own code if it's not properly indented, so you want to clean it up so that working on your code remains pleasant and productive.

Tutte le indentazioni di un dato blocco devono essere consistenti e non è possibile tagliare un blocco. I codici seguenti sono incorretti e solleveranno errori.

if condizione:
    cosaFare()
     cosaFareInSeguito() # uno spazio di troppo
cosaFareComunque()
if condizione:
    cosaFare()
cosaFareComunque()
    cosaFareInSeguito() # questo blocco non segue le righe della condizione

The condition must be a [!c]int[/!][!java]boolean[/!][!scala|python]Boolean[/!] expression. The inner block of code will get executed if the expression is evaluated to [!c]1[/!][!java|scala]true[/!][!python]True[/!] and it will be ignored if it is [!c]0[/!][!java|scala]false[/!][!python]False[/!]. [!python|scala|java][!java|scala]true[/!][!python]True[/!] and [!java|scala]false[/!][!python]False[/!] are constant values defined by [!thelang] directly, just as 0 or 1 in mathematics.[/!]

The condition can be a [!c]int[/!][!java]boolean[/!][!scala|python]Boolean[/!] variable (we will come back on variables in a later exercise, don't worry) or an arithmetic test, such as x == 5, which checks whether the current value of x is 5, or such as != (checking inequality, that is, returning [!c]1[/!][!java|scala]true[/!][!python]True[/!] only if the left-hand side is different from the right-hand side), < (smaller than), > (larger than), <= (smaller or equal to), >= (larger or equal to).

Beware of the classical trap, which consists in testing the equality of a variable using = instead of ==. Hopefully, the [!java|scala|c]compiler[/!][!python]interpreter[/!] detects this problem most of the time, but it could get trapped is some cases (such as when you are affecting a [!c]int[/!][!java|python|scala]boolean[/!] variable). So you'd better to be careful...

The condition can also be a call to some particular methods returning a boolean. For example, the isFacingWall() method of the buggle returns [!c]1[/!][!java|python|scala]true[/!] if the buggle is facing a wall, and [!c]0[/!][!java|python|scala]false[/!] in the other case.

Infine una condizione può essere composta da altre condizioni interconnesse da operazioni booleane:

Concludendo, è possibile anche specificare cosa bisogna fare quando la condizione è falsa attraverso la seguente sintassi. In questo caso l'istruzione cosaFareSeFalso() sarà eseguita solo nella condizione false.

[!java|scala|c]if (condition) {
    whatToDoIfTheConditionIsTrue();
} else {
    whatToDoIfItsFalse();
}[/!][!python]if (condition):
    whatToDoIfTheConditionIsTrue()
else:
    whatToDoIfItsFalse()[/!]

Non dimenticate i duepunti (:) dopo l'else, essi indicano che un nuovo blocco sta iniziando.

Traguardo dell'esercizio

Se il buggle fronteggia un muro bisogna fare un passo indietro. Alrimenti bisogna fare un passo avanti. Per rilevare se si ha un muro difronte basta usare il metodo predefinito isFacingWall() che ogni buggle capisce.

Questo esercizio è un po'differente: il tuo codice funziona per più buggle, ognuno di loro è in una propria situazione iniziale. Lo stesso codice sarà eseguito per ognuno di loro.

Quando il tuo programma funzionerà, vai avanti al prossimo esercizio che è nel prossimo sotto-albero della selection windows.