티스토리 뷰
Conditionals¶
Reference¶
https://github.com/JuliaComputing/JuliaBoxTutorials/tree/master/introductory-tutorials/intro-to-julia (github : JuliaComputing/JuliaBoxTutorials/introductory-tutorials/intro-to-julia/)
Topics:
함께보기¶
- http://deepstat.tistory.com/45 (01. Getting started)(in English)
- http://deepstat.tistory.com/46 (01. Getting started(한글))
- http://deepstat.tistory.com/47 (02. Strings)(in English)
- http://deepstat.tistory.com/48 (02. Strings(한글))
- http://deepstat.tistory.com/49 (03. Data structures)(in English)
- http://deepstat.tistory.com/50 (03. Data structures(한글))
- http://deepstat.tistory.com/51 (04. Loops)(in English)
- http://deepstat.tistory.com/52 (04. Loops(한글))
- http://deepstat.tistory.com/53 (05. Conditionals)(in English)
if 문 ¶
줄리아에서, 구문
if *condition 1*
*option 1*
elseif *condition 2*
*option 2*
else
*option 3*
end
을 사용하면 조건부로 옵션 중 하나를 실행할 수 있다.
예를 들어서, 숫자 N이 주어졌을 때, 3의 배수면 "피즈", 5의 배수면 "버즈", 3의 배수인 동시에 5의 배수면 "피즈버즈", 아무것도 아니면 숫자 그대로 출력하는 작업을 하고 싶다고 하자.
N = 3
if (N % 3 == 0) && (N % 5 == 0) # `&&` 는 "AND"를 의미하고, %는 나눈 나머지를 의미한다.
println("피즈버즈")
elseif N % 3 == 0
println("피즈")
elseif N % 5 == 0
println("버즈")
else
println(N)
end
N = 5
if (N % 3 == 0) && (N % 5 == 0) # `&&` 는 "AND"를 의미하고, %는 나눈 나머지를 의미한다.
println("피즈버즈")
elseif N % 3 == 0
println("피즈")
elseif N % 5 == 0
println("버즈")
else
println(N)
end
N = 15
if (N % 3 == 0) && (N % 5 == 0) # `&&` 는 "AND"를 의미하고, %는 나눈 나머지를 의미한다.
println("피즈버즈")
elseif N % 3 == 0
println("피즈")
elseif N % 5 == 0
println("버즈")
else
println(N)
end
N = 1
if (N % 3 == 0) && (N % 5 == 0)
println("피즈버즈")
elseif N % 3 == 0
println("피즈")
elseif N % 5 == 0
println("버즈")
else
println(N)
end
삼항연산자 ¶
삼항연산자 구문은 다음과 같다.
a ? b : c
이 구문은 아래 구문과 같은 역할을 한다.
if a
b
else
c
end
x, y 두 숫자가 주어졌을 때, 더 큰 값을 출력하는 작업을 하고싶다고 하자.
x = 1
y = 2
if else 문을 쓰면 다음과 같다.
if x > y
x
else
y
end
삼항연산자를 사용하면 다음과 같다.
(x > y) ? x : y
x = 2
y = 1
if x > y
x
else
y
end
(x > y) ? x : y
short-circuit evaluation ¶
short-circuit evaluation은 논리연산에서 왼쪽 항의 특정 조건이 만족되면 오른쪽 항을 굳이 연산하지 않는 것을 의미한다.
우리는 아래 논리연산자를 이미 본 적 있다.
a && b
이 구문은 a와 b 둘 다 true일 때만 true를 내보낸다. 만일 a 가 false이면, b에 상관없이 연산 결과가 false이다. 따라서 Julia는 b와 상관없이, 그냥 false를 내보낸다. 이 방식에는 약간의 부작용이 있는데, 아래 코드를 실행 해보면 알 수 있다.
false && (println("안녕"); true)
true && (println("안녕"); true)
아래처럼 뒤에 에러를 반환하는 함수를 써서 적용할 수도 있다.
x = 1
(x > 0) && error("x 는 0보다 클 수 없다.")
x = -1
(x > 0) && error("x는 0보다 클 수 없다.")
비슷하게, || 연산에 대해서도 가능하다.
true || println("안녕")
false || println("안녕")
Exercises ¶
5.1¶
숫자가 짝수이면 숫자를 출력하고 숫자가 홀수이면 "홀수"를 출력하는 코드를 작성해보자.
n = 1
if n % 2 == 1
println("홀수")
else
println(n)
end
n = 2
if n % 2 == 1
println("홀수")
else
println(n)
end
5.2¶
삼항연산자를 써서 위의 코드를 다시 써보자.
n = 1
(n % 2 == 1) ? println("홀수") : n
n = 2
(n % 2 == 1) ? println("홀수") : n
'Flux in Julia > Learning Julia (Intro_to_Julia)' 카테고리의 다른 글
06. Functions (한글) (0) | 2018.09.27 |
---|---|
06. Functions (0) | 2018.09.27 |
05. Conditionals (0) | 2018.09.18 |
04. Loops (한글) (0) | 2018.09.15 |
04. Loops (0) | 2018.09.15 |