Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 407
Shayan Avatar asked Nov 24 '25 23:11

Shayan


1 Answers

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.

like image 186
Bogumił Kamiński Avatar answered Nov 26 '25 14:11

Bogumił Kamiński



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!