Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading