개발/python
[2020.07.15] python 입출력, 제어문,반복문
서니소니
2020. 7. 15. 17:29
input() : console에서 입력받음
print() : console로 출력
my_input = input("입력값을 넣으세요 : ")
print(type(my_input), end=" ") # end= , 줄바꿈 대신 출력
print(my_input)
#기본적으로 print() 함수는 한줄을 출력한 후 line feed(줄바꿈)를 수행
#줄바꿈 대신 다른 문자를 출력하려면 'end=' 속성을 이용
Control Statement(제어문)
1. if문
a = 15
if a % 3 == 0:
#print("3의 배수입니다.")
pass # 아무것도 안하고 넘어감, 빈 칸으로 둘 경우 에러남
elif a % 5 == 0:
print("5의 배수입니다.")
else:
print("3의 배수도 아니고 5의 배수도 아닙니다.")
2. in
in을 이용한 구문
my_list = ["서울", "인천", "부산"]
if "수원" in my_list:
pass
else:
print("수원은 지역안에 없어요")
반복문 - for, while ( do ~ while은 존재x)
for문의 두가지 형태
for ~ in range() # 반복횟수를 지정한 경우
for ~ in list, tuple,dict 같은 집합자료구조 # 가지고 있는 데이터만큼 반복
1부터 100까지 합
my_sum = 0
for tmp in range(1, 101, 1):
my_sum += tmp
print("누적값은 : {}".format(my_sum))
집합자료형을 이용해서 for문 수행
- list
my_list = ["서울", "인천", "부산"]
for tmp in my_list:
print(tmp)
- tuple
my_data = [(1, 2), (3, 4), (5, 6)]
total = 0
for (tmp1, tmp2) in my_data:
total += (tmp1 + tmp2)
print(total)
* list comprehension : 하나의 자료형으로 다른 list 를 쉽게 생성하는 방법
my_list = [1, 2, 3, 4, 5]
# goal = [2, 4, 6, 8, 10] 만들기
# 기존 방법
goal = list() # []
for tmp in my_list:
goal.append(tmp*2)
print(goal)
# list comprehension
my_list = [1, 2, 3, 4, 5]
goal = [tmp*2 for tmp in my_list]
print(goal)
# 짝수만 뽑아내기
my_list = [1, 2, 3, 4, 5]
goal = [tmp for tmp in my_list if tmp % 2 == 0]
print(goal) # [2, 4]
while문
idx = 0
while idx < 10:
print("현재 idx의 값은 : {}".format(idx))
idx += 1