Questions tagged [if-statement]

An "if" statement is a flow control structure in most programming languages that branches execution flow depending on a binary condition, generally evaluated at runtime. If statements are also commonly also called conditionals. When using this tag please also include an appropriate language tag, such as e.g. "java" if your question is language-specific.

An if statement is a flow control structure in most programming languages that branches execution flow depending on a binary condition, generally evaluated at runtime. If-statements are also commonly known as conditionals.

When using this tag please also include an appropriate language tag, such as e.g. if your question is language-specific.


Basic Syntax

The if statement has the following syntax:

if <condition>
then
     <statement-1>
else
     <statement-2>

<condition> may be parenthesized (as it is in JavaScript), the keyword then may be omitted (Python, C-like languages, JavaScript and others).

The else section is optional in most languages.

An example if statement in JavaScript:

var myVariable = 100;

if (myVariable >= 20) {
    console.log('My variable is greater than or equal to 20!');
} else {
    console.log('My variable is less than 20!');
}

if-else statements may also be nested, where another if may appear in if statement, and/or in else statement. For example:

if ( number1 > 20 )
   if ( number2 > 50 )
      print('Both numbers satisfy condition')
   else
      print('Second number doesn't satisfy condition')
else
   if( number2 > 50 )
      print('Only Second number satisfies condition')
   else
      print('None of the two numbers satisfy condition')

else+if is used to chain if statements:

if ( number > 20 )
     print('Greater than 20')
else+if ( number > 10 )
     print('Greater than 10')
else
     print('Less than 11')

else+if statements may simply be an else statement followed by an if (e.g else if; done in JavaScript and many C-like languages), or a special keyword such as elif (Python), or elsif (Perl).


As a ternary operator

In C and C-like languages, conditional expressions can take the form of a ternary operator called the conditional expression operator, ?:, which follows this template:

(condition)?(evaluate if condition was true):(evaluate if condition was false)

In Python, if is used explicitly, and the ordering is slightly different:

(evaluate if condition was true) if (condition) else (evaluate if condition was false)

An example of the ternary operator in JavaScript:

var myVariable = 100;

myVariable>20 ? console.log('Greater than 20!') : console.log('Less than or equal to 20!');

See also:

52698 questions
1608
votes
31 answers

How do I perform an IF...THEN in an SQL SELECT?

How do I perform an IF...THEN in an SQL SELECT statement? For example: SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product
Eric Labashosky
  • 27,105
  • 12
  • 37
  • 32
1048
votes
5 answers

Putting a simple if-then-else statement on one line

I'm just getting into Python and I really like the terseness of the syntax. However, is there an easier way of writing an if-then-else statement so it fits on one line? For example: if count == N: count = 0 else: count = N + 1 Is there a…
Abizern
  • 129,329
  • 36
  • 198
  • 252
906
votes
10 answers

Python's equivalent of && (logical-and) in an if-statement

Here's my code: def front_back(a, b): # +++your code here+++ if len(a) % 2 == 0 && len(b) % 2 == 0: return a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):] else: #todo! Not yet done. :P return I'm getting an error…
delete
755
votes
19 answers

How to use *ngIf else?

I'm using Angular and I want to use *ngIf else (available since version 4) in this example:
content here ...
other content here...
How can I acheive the same behavior with ngIf else ?
El houcine bougarfaoui
  • 29,581
  • 7
  • 34
  • 35
749
votes
30 answers

Styling multi-line conditions in 'if' statements?

Sometimes I break long conditions in ifs onto several lines. The most obvious way to do this is: if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something Isn't very very appealing visually,…
Eli Bendersky
  • 231,995
  • 78
  • 333
  • 394
724
votes
27 answers

How to test multiple variables against a single value?

I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say: x = 0 y = 1 z = 3 mylist = [] if x or y or z == 0 : …
user1877442
  • 7,431
  • 3
  • 11
  • 5
708
votes
10 answers

if else statement in AngularJS templates

I want to do a condition in an AngularJS template. I fetch a video list from the Youtube API. Some of the videos are in 16:9 ratio and some are in 4:3 ratio. I want to make a condition like this: if video.yt$aspectRatio equals widescreen then …
vzhen
  • 10,891
  • 13
  • 51
  • 82
699
votes
9 answers

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

A co-worker claimed recently in a code review that the [[ ]] construct is to be preferred over [ ] in constructs like if [ "`id -nu`" = "$someuser" ] ; then echo "I love you madly, $someuser" fi He couldn't provide a rationale. Is there one?
Leonard
  • 11,612
  • 8
  • 41
  • 69
664
votes
12 answers

How do I compare two string variables in an 'if' statement in Bash?

I'm trying to get an if statement to work in Bash (using Ubuntu): #!/bin/bash s1="hi" s2="hi" if ["$s1" == "$s2"] then echo match fi I've tried various forms of the if statement, using [["$s1" == "$s2"]], with and without quotes, using =, ==…
Mr Shoubs
  • 12,813
  • 15
  • 63
  • 103
588
votes
8 answers

How to do a logical OR operation for integer comparison in shell scripting?

I am trying to do a simple condition check, but it doesn't seem to work. If $# is equal to 0 or is greater than 1 then say hello. I have tried the following syntax with no success: if [ "$#" == 0 -o "$#" > 1 ] ; then echo "hello" fi if [ "$#" == 0…
Strawberry
  • 58,930
  • 53
  • 138
  • 190
563
votes
22 answers

Why does python use 'else' after for and while loops?

I understand how this construct works: for i in range(10): print(i) if i == 9: print("Too big - I'm giving up!") break; else: print("Completed successfully") But I don't understand why else is used as the keyword here,…
Kent Boogaart
  • 165,446
  • 34
  • 376
  • 376
534
votes
8 answers

if else in a list comprehension

I have a list l: l = [22, 13, 45, 50, 98, 69, 43, 44, 1] For numbers above 45 inclusive, I would like to add 1; and for numbers less than it, 5. I tried [x+1 for x in l if x >= 45 else x+5] But it gives me a syntax error. How can I achieve an if –…
user225312
  • 108,033
  • 64
  • 161
  • 179
463
votes
7 answers

jQuery if checkbox is checked

I have a function below that I want to only trigger when a checkbox in the same tr is checked. Please tell me what I am doing wrong, the usual methods are not working. Thanks JS $(".add_menu_item_table").live('click', function() { var value_td =…
Clinton Green
  • 8,667
  • 15
  • 60
  • 101
443
votes
14 answers

How to write inline if statement for print?

I need to print some stuff only when a boolean variable is set to True. So, after looking at this, I tried with a simple example: >>> a = 100 >>> b = True >>> print a if b File "", line 1 print a if b ^ SyntaxError: invalid…
Ricky Robinson
  • 17,881
  • 35
  • 113
  • 172
388
votes
5 answers

if, elif, else statement issues in Bash

I can't seem to work out what the issue with the following if statement is in regards to the elif and then. Keep in mind the printf is still under development I just haven't been able to test it yet in the statement so is more than likely wrong. The…
StuStirling
  • 14,067
  • 20
  • 82
  • 138
1
2 3
99 100