Questions tagged [conditional-statements]
"In computer science, conditional statements, conditional expressions and conditional constructs are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false. Apart from the case of branch prediction, this is always achieved by selectively altering the control flow based on some condition." -- Wikipedia
19,302
questions
2300
votes
28
answers
1.1m
views
How to write a switch statement in Ruby
How do I write a switch statement in Ruby?
584
votes
15
answers
1.3m
views
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
...
564
votes
35
answers
1.2m
views
Check whether a String is not Null and not Empty
How can I check whether a string is not null and not empty?
public void doStuff(String str)
{
if (str != null && str != "**here I want to check the 'str' is empty or not**")
{...
465
votes
4
answers
2.1m
views
Check if something is (not) in a list in Python
I have a list of tuples in Python, and I have a conditional where I want to take the branch ONLY if the tuple is not in the list (if it is in the list, then I don't want to take the if branch)
if ...
408
votes
33
answers
915k
views
Laravel Checking If a Record Exists
I am new to Laravel. How do I find if a record exists?
$user = User::where('email', '=', Input::get('email'));
What can I do here to see if $user has a record?
383
votes
32
answers
636k
views
How to use conditional statement within child attribute of a Flutter Widget (Center Widget)
So far whenever I needed to use a conditional statement within a Widget I have done the following (Using Center and Containers as simplified dummy examples):
new Center(
child: condition == true ? ...
285
votes
5
answers
235k
views
What command means "do nothing" in a conditional in Bash?
Sometimes when making conditionals, I need the code to do nothing, e.g., here, I want Bash to do nothing when $a is greater than "10", print "1" if $a is less than "5", otherwise, print "2":
if [ "$a"...
281
votes
5
answers
224k
views
How do I negate a test with regular expressions in a bash script?
Using GNU bash (version 4.0.35(1)-release (x86_64-suse-linux-gnu), I would like to negate a test with Regular Expressions. For example, I would like to conditionally add a path to the PATH variable, ...
279
votes
8
answers
611k
views
Replace all elements of NumPy array that are greater than some value
I have a 2D NumPy array. How do I replace all values in it greater than a threshold T = 255 with a value x = 255? A slow for-loop based method would be:
# arr = arr.copy() # Optionally, do not modify ...
238
votes
4
answers
100k
views
Why is the use of len(SEQUENCE) in condition values considered incorrect by Pylint?
Considering this code snippet:
from os import walk
files = []
for (dirpath, _, filenames) in walk(mydir):
# More code that modifies files
if len(files) == 0: # <-- C1801
return None
I was ...
206
votes
5
answers
714k
views
How to combine multiple conditions to subset a data-frame using "OR"?
I have a data.frame in R. I want to try two different conditions on two different columns, but I want these conditions to be inclusive. Therefore, I would like to use "OR" to combine the conditions. ...
206
votes
3
answers
75k
views
Are "elseif" and "else if" completely synonymous?
Are elseif and else if completely synonymous, or is there a difference?
Does Zend have an accepted "standard" on which one to use?
While I personally dislike seeing elseif in the code, I just need ...
203
votes
7
answers
163k
views
Why do empty JavaScript arrays evaluate to true in conditional structures?
I was encountering a lot of bugs in my code because I expected this expression:
Boolean([]); to evaluate to false.
But this wasn't the case as it evaluated to true.
Therefore, functions that possibly ...
202
votes
6
answers
431k
views
Conditional Replace Pandas [duplicate]
I have a DataFrame, and I want to replace the values in a particular column that exceed a value with zero. I had thought this was a way of achieving this:
df[df.my_channel > 20000].my_channel = 0
...
200
votes
9
answers
170k
views
Javascript switch vs. if...else if...else
Guys I have a couple of questions:
Is there a performance difference in JavaScript between a switch statement and an if...else?
If so why?
Is the behavior of switch and if...else different across ...
197
votes
3
answers
142k
views
Conditional import of modules in Python [duplicate]
In my program I want to import simplejson or json based on OS being Linux or Windows. I take the OS name as input from the user. Now, is it correct to do it with a condition like this?
osys = ...
186
votes
19
answers
946k
views
Can you use if/else conditions in CSS?
I would like to use conditions in my CSS.
The idea is that I have a variable that I replace when the site is run to generate the right style-sheet.
I want it so that according to this variable the ...
173
votes
8
answers
400k
views
Creating a new column based on if-elif-else condition [duplicate]
I have a DataFrame df:
A B
a 2 2
b 3 1
c 1 3
I want to create a new column based on the following criteria:
if row A == B: 0
if rowA > B: 1
if row A < B: -1
so ...
172
votes
4
answers
10k
views
An expensive jump with GCC 5.4.0
I had a function which looked like this (showing only the important part):
double CompareShifted(const std::vector<uint16_t>& l, const std::vector<uint16_t> &curr, int shift, int ...
161
votes
12
answers
145k
views
Is it good practice to use the xor operator for boolean checks? [closed]
I personally like the exclusive or, ^, operator when it makes sense in the context of boolean checks because of its conciseness. I much prefer to write
if (boolean1 ^ boolean2)
{
//do it
}
than
...
156
votes
7
answers
126k
views
Inline conditions in Lua (a == b ? "yes" : "no")?
Is there anyway to use inline conditions in Lua?
Such as:
print("blah: " .. (a == true ? "blah" : "nahblah"))
150
votes
12
answers
14k
views
If condition A is matched, condition B needs to be matched in order to do action C
My question is:
if (/* condition A */)
{
if(/* condition B */)
{
/* do action C */
}
else
/* ... */
}
else
{
/* do action C */
}
Is it possible to just write ...
145
votes
10
answers
89k
views
Determining if a variable is within range?
I need to write a loop that does something like:
if i (1..10)
do thing 1
elsif i (11..20)
do thing 2
elsif i (21..30)
do thing 3
etc...
But so far have gone down the wrong paths in terms of ...
145
votes
14
answers
312k
views
JavaScript: using a condition in switch case
How can I use a condition inside a switch statement for JavaScript?
In the example below, a case should match when the variable liCount is <= 5 and > 0; however, my code does not work:
switch (...
144
votes
8
answers
277k
views
Can I use conditional statements with EJS templates (in JMVC)?
and if yes, what is the syntax?
My goal is to prepend an 's' to the word 'comment' when there is more than one. in an jQuery.ejs template in a JMVC app. The following breaks. I can't find any docs for ...
144
votes
10
answers
459k
views
Set value of one Pandas column based on value in another column
I need to set the value of one column based on the value of another in a Pandas dataframe. This is the logic:
if df['c1'] == 'Value':
df['c2'] = 10
else:
df['c2'] = df['c3']
I am unable to ...
144
votes
10
answers
38k
views
Conditional with statement in Python
Is there a way to begin a block of code with a with statement, but conditionally?
Something like:
if needs_with():
with get_stuff() as gs:
# do nearly the same large block of stuff,
# involving ...
137
votes
6
answers
290k
views
Replacing Numpy elements if condition is met
I have a large numpy array that I need to manipulate so that each element is changed to either a 1 or 0 if a condition is met (will be used as a pixel mask later). There are about 8 million elements ...
130
votes
19
answers
434k
views
IF... OR IF... in a windows batch file
Is there a way to write an IF OR IF conditional statement in a windows batch-file?
For example:
IF [%var%] == [1] OR IF [%var%] == [2] ECHO TRUE
129
votes
9
answers
204k
views
IN Clause with NULL or IS NULL
Postgres is the database
Can I use a NULL value for a IN clause? example:
SELECT *
FROM tbl_name
WHERE id_field IN ('value1', 'value2', 'value3', NULL)
I want to limit to these four values.
I have ...
129
votes
14
answers
158k
views
How to compare strings in C conditional preprocessor-directives
I have to do something like this in C. It works only if I use a char, but I need a string. How can I do this?
#define USER "jack" // jack or queen
#if USER == "jack"
#define USER_VS "queen"
#elif ...
127
votes
3
answers
92k
views
MySQL IN condition limit
Hey, I have to use IN condition in my MySQL statement with a large set of ids.
Example
SELECT * FROM users WHERE id IN (1,2,3,4...100000)
Is there a limit if items the IN statement can have?
121
votes
7
answers
431k
views
VBA - how to conditionally skip a for loop iteration
I have a for loop over an array. What I want to do is test for a certain condition in the loop and skip to the next iteration if true:
For i = LBound(Schedule, 1) To UBound(Schedule, 1)
If (...
117
votes
6
answers
309k
views
MySQL select with CONCAT condition
I'm trying to compile this in my mind.. i have a table with firstname and lastname fields
and i have a string like "Bob Jones" or "Bob Michael Jones" and several others.
the thing is, i have for ...
115
votes
3
answers
183k
views
Syntax for if/else condition in SCSS mixin
Hi I'm trying to learn SASS/SCSS and am trying to refactor my own mixin for clearfix
what I'd like is for the mixin to be based on whether I pass the mixin a width.
thoughts so far (pseudo code only ...
115
votes
3
answers
436k
views
querying WHERE condition to character length?
I have a database with a large number of words but i want to select only those records where the character length is equal to a given number (in example case 3):
$query = ("SELECT * FROM $db WHERE ...
114
votes
14
answers
588k
views
How to check whether a str(variable) is empty or not?
How do I make a:
if str(variable) == [contains text]:
condition?
(or something, because I am pretty sure that what I just wrote is completely wrong)
I am sort of trying to check if a random....
113
votes
8
answers
86k
views
#ifdef #ifndef in Java
I doubt if there is a way to make compile-time conditions in Java like #ifdef #ifndef in C++.
My problem is that have an algorithm written in Java, and I have different running time improves to that ...
112
votes
4
answers
108k
views
How does "do something OR DIE()" work in PHP?
I'm writing a php app to access a MySQL database, and on a tutorial, it says something of the form
mysql_connect($host, $user, $pass) or die("could not connect");
How does PHP know that the function ...
111
votes
11
answers
154k
views
Dart null / false / empty checking: How to write this shorter?
This is my code for true on everything but empty string, null and false:
if (routeinfo["no_route"] == "" || routeinfo["no_route"] == null || routeinfo["no_route"] == false) {
// do sth ...
}
...
110
votes
13
answers
115k
views
MySQL Conditional Insert
I am having a difficult time forming a conditional INSERT
I have x_table with columns (instance, user, item) where instance ID is unique. I want to insert a new row only if the user already does not ...
109
votes
4
answers
86k
views
Angular 2 Pipe under condition
Is it possible in Angular 2 to apply a pipe under condition?
I would like to do something like:
{{ variable.text | (variable.value ? SomePipe : OtherPipe) }}
If not, what is the preferred way to ...
109
votes
10
answers
97k
views
Conditional build based on environment using Webpack
I have some things for development - e.g mocks which I would like to not bloat my distributed build file with.
In RequireJS you can pass a config in a plugin file and conditonally require things in ...
106
votes
4
answers
154k
views
In Twig, check if a specific key of an array exists
In PHP we can check if a key exists in an array by using the function array_key_exists().
In the Twig templating language we can check if an variable or an object's property exists simply by using an ...
105
votes
10
answers
331k
views
Run an Ansible task only when the variable contains a specific string
I have multiple tasks depend from the value of variable1. I want to check if the value is in {{ variable1 }} but I get an error:
- name: do something when the value in variable1
command: <command&...
104
votes
13
answers
42k
views
Determining if a number is either a multiple of ten or within a particular set of ranges
I have a few loops that I need in my program. I can write out the pseudo code, but I'm not entirely sure how to write them logically.
I need -
if (num is a multiple of 10) { do this }
if (num is ...
101
votes
7
answers
156k
views
Check if year is leap year in javascript [duplicate]
function leapYear(year){
var result;
year = parseInt(document.getElementById("isYear").value);
if (years/400){
result = true
}
else if(years/100){
result = false
}
...
95
votes
12
answers
115k
views
Why would you use an assignment in a condition?
In many languages, assignments are legal in conditions. I never understood the reason behind this. Why would you write:
if (var1 = var2) {
...
}
instead of:
var1 = var2;
if (var1) {
...
}
?
95
votes
10
answers
107k
views
Swift inline conditional?
How do I do this in Swift ?
(someboolexpression ? "Return value 1" : "Return value 2")
(no I have not read the whole manual yet... I probably missed it on page 2!)
OK so its on page 91 and the ...
95
votes
4
answers
219k
views
How do use a Switch Case Statement in Dart
I am trying to understand how the switch is working in the dart. I have very simple code:
methodname(num radians) {
switch (radians) {
case 0:
// do something
break;
case PI:
...