In Objective-C, we would write an if statement like this:
if(number1 == number2){ NSLog(@"equal"); }
in Python it is this:
if number1==number2 : print('equal')
There is no parentheses required around the logical expression. Instead of the {} to show the block to run, a colon (:) and indentations find the code to run. Note that if you feel comfy putting parentheses around your logical expression, go ahead. Python will not complain.
A simple else statement is not more than that:
if (number1 == number2): print('equal') else: print('not equal')
Python gets a little different when there is more than one else. Python uses the elif operator , which stands for else if. Instead of this in XCode:
if (number1 == number2) { NSLog(@"equal"); } else if(number1 > number2){ NSLog(@"greater"); } else if( number1 < number2){ NSLog(@"less"); else{ NSLog(@"error"); }
We have in Python:
if number1 == number2: print('equal') elif number1 > number2: print('greater') elif number1 < number2: print('less') else: print('error')
Note the use of else here. Else is actually not required for chains of elif, but its use would be the same as default in a switch…case…default statement.
switch(number2){ case 1: //stuff break; case 2: //more stuff break; case 3:{ //even more stuff break; default: //none of that stuff, most likely an error. break; }
Leave a Reply