Shayan
Shayan

Reputation: 6295

or logical operator in julia

I'm trying to understand how Julia takes or operator. here is the script that I'm practicing with:

integer = 52
if length(string(integer)) == 1 || 2
    println("length is 1 or 2")
end

but it gives me this error:

TypeError: non-boolean (Int64) used in boolean context

Stacktrace:
 [1] top-level scope
   @ In[108]:2
 [2] eval
   @ .\boot.jl:373 [inlined]
 [3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base .\loading.jl:1196

and I'm sure the problem is where I wrote 1 || 2! how should I specify it in Julia? and how should I interpret TypeError: non-boolean (Int64) used in boolean context error?

Upvotes: 3

Views: 4496

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69879

You should write:

length(string(integer)) in [1, 2]

or

1 <= length(string(integer)) <= 2

or more verbosely:

length(string(integer)) == 1 || length(string(integer)) == 2

When you write:

length(string(integer)) == 1 || 2

it gets interpreted as "length(string(integer)) == 1" or "2". Since the length of your string is not 1 the value of the whole expression is 2 and 2 is not Bool. You get an error because you try to use non-boolean value in the condition.

You can check that this is indeed what happens by evaluating:

julia> length(string(integer)) == 1 || 2
2

This behavior is explained here in the Julia Manual.

Upvotes: 4

Related Questions