if문의 구조 #
# a라는 변수 정의
>>> a = 3
# a변수의 값의 유무 체크
>>> if a:
. . . print(‘there is a’)
. . . else:
. . . print(‘there is no a’)
. . .
there is a
비교 연산자 #
>>> a = 3
>>> b = 2
>>> a > b # a보다 b가 작다
True
>>> a < b # a보다 b가 크다
False
>>> a == b # a와 b가 같다
False
>>> a != b # a와 b가 같지 않다
True
>>> money = 2000
>>> if money >= 5000:
. . . print(‘택시를 타고 갑시다’)
. . . else:
. . . print(‘걸어 갑시다’)
. . .
걸어 갑시다
is 와 ==의 차이 #
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
>>> b == a
True
>>> b = a[:]
>>> b is a
False
>>> b == a
True
>>> 1000 is 10**3
False
>>> 1000 == 10**3
True
>>> ‘a’ is ‘a’
True
>>> ‘aa’ is ‘a’ * 2
True
>>> x = ‘a’
>>> ‘aa’ is x * 2
False
x in s, x not in s #
>>> 1 in [1, 2, 3]
True
>>> 1 not in [1, 2, 3]
False
>>> ‘a’ in (‘a’, ‘b’, ‘c’)
True
>>> ‘j’ not in ‘python’
True
다양한 조건을 판단하는 elif #
>>> x = int(input(‘Please enter an integer: ‘))
Please enter an integer: 42
>>> if x < 0:
. . . x = 0
. . . print(‘Negative changed to zero’)
. . . elif x == 0:
. . . print(‘Zero’)
. . . elif x == 1:
. . . print(‘Single’)
. . . else:
. . . print(‘More’)
. . .
More
연습문제 답 #
1. 섭씨와 화씨를 변환하는 파이썬 프로그램을 작성하시오 #
temp = input("Input the temperature you like to convert? (e.g., 45F, 102C etc.) : ")
degree = int(temp[:-1])
i_convention = temp[-1]
if i_convention.upper() == "C":
result = int(round((9 * degree) / 5 + 32))
o_convention = "Fahrenheit"
elif i_convention.upper() == "F":
result = int(round((degree - 32) * 5 / 9))
o_convention = "Celsius"
else:
print("Input proper convention.")
quit()
print("The temperature in", o_convention, "is", result, "degrees.")
2. 1500에서 2700사이(양 끝수 포함)의 수 중 7로 나누어 떨어지고 5의 배수인 수를 찾는 파이썬 프로그램을 작성하시오. #
nl=[]
for x in range(1500, 2700):
if (x%7==0) and (x%5==0):
nl.append(str(x))
print (','.join(nl))