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:

61703 questions
1775
votes
29 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
  • 29,484
  • 14
  • 39
  • 32
1318
votes
5 answers

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

How do I write an if-then-else statement in Python so that it fits on one line? For example, I want a one line version of: if count == N: count = 0 else: count = N + 1 In Objective-C, I would write this as: count = count == N ? 0 : count +…
Abizern
  • 146,289
  • 39
  • 203
  • 257
974
votes
22 answers

How can I 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 achieve the same behavior with ngIf else?
El houcine bougarfaoui
  • 35,805
  • 9
  • 37
  • 37
896
votes
10 answers

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

A coworker 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
  • 13,269
  • 9
  • 45
  • 72
862
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
  • 263,248
  • 89
  • 350
  • 412
837
votes
31 answers

How to test multiple variables for equality 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
  • 8,561
  • 3
  • 13
  • 5
809
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
  • 14,629
  • 17
  • 68
  • 107
727
votes
25 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
  • 175,602
  • 35
  • 392
  • 393
727
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
  • 11,137
  • 13
  • 56
  • 87
663
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
  • 126,773
  • 69
  • 172
  • 181
593
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
  • 66,024
  • 56
  • 149
  • 197
583
votes
13 answers

How to check the exit status using an 'if' statement

What would be the best way to check the exit status in an if statement in order to echo a specific output? I'm thinking of it being: if [ $? -eq 1 ] then echo "blah blah blah" fi The issue I am also having is that the exit statement is before…
deadcell4
  • 6,085
  • 3
  • 14
  • 10
569
votes
15 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
  • 21,798
  • 42
  • 129
  • 185
519
votes
11 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
  • 9,697
  • 21
  • 68
  • 103
469
votes
9 answers

Does Go have "if x in" construct similar to Python?

How can I check if x is in an array without iterating over the entire array, using Go? Does the language have a construct for this? Like in Python: if "x" in array: # do something
user1529891
1
2 3
99 100