How to Read About Conditionals Done with "" and ":" (Colon)

Where can I read about conditionals done with ? and : (colon)?

It's the Ternary Operator.

Basic usage is something like

$foo = (if this expressions returns true) ? (assign this value to $foo) : (otherwise, assign this value to $foo)

It can be used for more than assignment though, it looks like other examples are cropping up below.

I think the reason you see this in a lot of modern, OO style PHP is that without static typing you end up needing to be paranoid about the types in any particular variable, and a one line ternary is less cluttered than a 7 line if/else conditional.

Also, in deference to the comments and truth in naming, read all about the ternary operators in computer science.

How to split string with colons but not if it is a time?

Why it isn't working:
You're asking it to search the entire string s for one pattern, ur"([:])".

If a match is found, you want it to search the entire string s again, but this time for the pattern ur"([0-9]|[2][0-3]):([0-5][0-9])".

If the first pattern is found, but the second pattern is not found, the substitution re.sub(':', ':\n', s) is made, replacing all ':' in s with ':\n'.

What you probably want to do is either:
1) Combine a negative lookbehind (?<!...) with a negative lookahead (?!...) in your pattern to define a pattern which describes "colons but not if it's a time".

or
2) Search the string for a colon, then search the region around that match to see if the match is part of a time; if not, replace that item.

Certainly (1) is more efficient, but implementing (2) will help you understand why your solution isn't working.

This may be helpful:

https://docs.python.org/3/library/re.html#re.search

Solution to #1:
The complete match pattern you're looking to replace should be:

(?<!(\b[0-1]?[0-9]|[2][0-3])):(?!([0-5][0-9])((?i)(am)|(pm))?\b)
So your one-liner would be:

s = re.sub(r'(?<!(\b[0-1]?[0-9]|[2][0-3])):(?!([0-5][0-9])((?i)(am)|(pm))?\b)', ':\n', s)
(Aren't regular expressions just so aesthetically pleasing?)

Try plugging it in here to test: https://www.debuggex.com/

(Remember to switch to Python in the dropdown menu.)

EDIT:
I forgot Python's lookbehinds have to be fixed width. A sloppy fix is to use the pattern:

(?<!([0-1\b][0-9]|[2][0-3])):(?!([0-5][0-9])((?i)(am)|(pm))?\b)
The caveat here is that it recognizes "garbage like11:45 and whatnot" as containing a time, but correctly identifies that "garbage like1:45 and whatnot" does not contain a time.

EDIT #2:
A little further checking shows that Javascript doesn't support lookbehinds at all, so many online regex testers might fail to execute this, even if you toggle them into Python mode.

What does the colon (:) operator do?

There are several places colon is used in Java code:

1) Jump-out label (Tutorial):

label: for (int i = 0; i < x; i++) {
for (int j = 0; j < i; j++) {
if (something(i, j)) break label; // jumps out of the i loop
}
}
// i.e. jumps to here

2) Ternary condition (Tutorial):

int a = (b < 4)? 7: 8; // if b < 4, set a to 7, else set a to 8

3) For-each loop (Tutorial):

String[] ss = {"hi", "there"}
for (String s: ss) {
print(s); // output "hi" , and "there" on the next iteration
}

4) Assertion (Guide):

int a = factorial(b);
assert a >= 0: "factorial may not be less than 0"; // throws an AssertionError with the message if the condition evaluates to false

5) Case in switch statement (Tutorial):

switch (type) {
case WHITESPACE:
case RETURN:
break;
case NUMBER:
print("got number: " + value);
break;
default:
print("syntax error");
}

6) Method references (Tutorial)

class Person {
public static int compareByAge(Person a, Person b) {
return a.birthday.compareTo(b.birthday);
}}
}

Arrays.sort(persons, Person::compareByAge);

How do you use the ? : (conditional) operator in JavaScript?

This is a one-line shorthand for an if-else statement. It's called the conditional operator.1

Here is an example of code that could be shortened with the conditional operator:

var userType;
if (userIsYoungerThan18) {
userType = "Minor";
} else {
userType = "Adult";
}

if (userIsYoungerThan21) {
serveDrink("Grape Juice");
} else {
serveDrink("Wine");
}

This can be shortened with the ?: like so:

var userType = userIsYoungerThan18 ? "Minor" : "Adult";

serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");

Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification:

userIsYoungerThan21 ? serveGrapeJuice() : serveWine();

They can even be chained:

serveDrink(userIsYoungerThan4 ? 'Milk' : userIsYoungerThan21 ? 'Grape Juice' : 'Wine');

Be careful, though, or you will end up with convoluted code like this:

var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j;

1 Often called "the ternary operator," but in fact it's just a ternary operator [an operator accepting three operands]. It's the only one JavaScript currently has, though.

Does Python have a ternary conditional operator?

Yes, it was added in version 2.5. The expression syntax is:

a if condition else b

First condition is evaluated, then exactly one of either a or b is evaluated and returned based on the Boolean value of condition. If condition evaluates to True, then a is evaluated and returned but b is ignored, or else when b is evaluated and returned but a is ignored.

This allows short-circuiting because when condition is true only a is evaluated and b is not evaluated at all, but when condition is false only b is evaluated and a is not evaluated at all.

For example:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'

Note that conditionals are an expression, not a statement. This means you can't use statements such as pass, or assignments with = (or "augmented" assignments like +=), within a conditional expression:

>>> pass if False else pass
File "<stdin>", line 1
pass if False else pass
^
SyntaxError: invalid syntax

>>> # Python parses this as `x = (1 if False else y) = 2`
>>> # The `(1 if False else x)` part is actually valid, but
>>> # it can't be on the left-hand side of `=`.
>>> x = 1 if False else y = 2
File "<stdin>", line 1
SyntaxError: cannot assign to conditional expression

>>> # If we parenthesize it instead...
>>> (x = 1) if False else (y = 2)
File "<stdin>", line 1
(x = 1) if False else (y = 2)
^
SyntaxError: invalid syntax

(In 3.8 and above, the := "walrus" operator allows simple assignment of values as an expression, which is then compatible with this syntax. But please don't write code like that; it will quickly become very difficult to understand.)

Similarly, because it is an expression, the else part is mandatory:

# Invalid syntax: we didn't specify what the value should be if the 
# condition isn't met. It doesn't matter if we can verify that
# ahead of time.
a if True

You can, however, use conditional expressions to assign a variable like so:

x = a if True else b

Or for example to return a value:

# Of course we should just use the standard library `max`;
# this is just for demonstration purposes.
def my_max(a, b):
return a if a > b else b

Think of the conditional expression as switching between two values. We can use it when we are in a 'one value or another' situation, where we will do the same thing with the result, regardless of whether the condition is met. We use the expression to compute the value, and then do something with it. If you need to do something different depending on the condition, then use a normal if statement instead.


Keep in mind that it's frowned upon by some Pythonistas for several reasons:

  • The order of the arguments is different from those of the classic condition ? a : b ternary operator from many other languages (such as C, C++, Go, Perl, Ruby, Java, JavaScript, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the argument order).
  • Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).
  • Stylistic reasons. (Although the 'inline if' can be really useful, and make your script more concise, it really does complicate your code)

If you're having trouble remembering the order, then remember that when read aloud, you (almost) say what you mean. For example, x = 4 if b > 8 else 9 is read aloud as x will be 4 if b is greater than 8 otherwise 9.

Official documentation:

  • Conditional expressions
  • Is there an equivalent of C’s ”?:” ternary operator?

VBA - How the colon `:` works in VBA code with condition

I think the confusion comes from 3. We'd think that 3 and 4 should behave the same. In fact, 3 is equivalent to this:

If 3 = 3 Then: (do nothing) 'an empty statement
Debug.Print 3 ' <-- This will be executed regardless of the previous If condition

To see it, change 3 into this:

If 3 = 0 Then:
Debug.Print 3 '<-- 3 will be printed! ;)

In conclusion, yes, the : is indeed to merge many statements on a single line

Good job @Vityata !!! :)

Syntax error on the colon in an if statement

It's not actually the colon. It's the unclosed bracket on the previous line.

When you get a weird SyntaxError, check for bracket balance before it.

Colon (:) in Python list index

: is the delimiter of the slice syntax to 'slice out' sub-parts in sequences , [start:end]

[1:5] is equivalent to "from 1 to 5" (5 not included)
[1:] is equivalent to "1 to end"
[len(a):] is equivalent to "from length of a to end"

Watch https://youtu.be/tKTZoB2Vjuk?t=41m40s at around 40:00 he starts explaining that.

Works with tuples and strings, too.

Short form for Java if statement

Use the ternary operator:

name = ((city.getName() == null) ? "N/A" : city.getName());

I think you have the conditions backwards - if it's null, you want the value to be "N/A".

What if city is null? Your code *hits the bed in that case. I'd add another check:

name = ((city == null) || (city.getName() == null) ? "N/A" : city.getName());


Related Topics



Leave a reply



Submit