[Python_basic]조건문, 반복문

Ronie🌊·2021년 1월 8일
0

Python👨🏻‍💻

목록 보기
4/11
post-thumbnail

git 바로가기


if
for
while
continue,break
한줄 for문


if

  • 조건문으로 다른 언어와 비슷하다.
  • 조건은 Boolean타입으로 정의 될 수 있는 값이면 뭐든 가능하다.
  • 예) a > b, a == b, a != b,True, False, 1, 0, .islower()
weather = input("how about weather? today?") #micro dust, sunny, rain
if weather == "rain" or weather == "snow":
    print("get your umbrella")
elif weather == "micro dust":
    print("get yout mask")
else:
     print("negative needs")
출력결과
how about weather? today?#입력값rain
get your umbrella

how about weather? today?#입력값snow
get your umbrell

for

  • 반복문의 기본형태
for 변수 in 리스트(또는 튜플, 문자열):
    수행할 문장1
for wating_no in range(1, 6): #1,2,3,4,5
    print("wating no : {0}" .format(wating_no))

starbucks = ["ironman","thor","grut"]
for customer in starbucks:
    print("{0}, ready to coffe." .format(customer))
출력결과
wating no : 1
wating no : 2
wating no : 3
wating no : 4
wating no : 5
ironman, ready to coffe.
thor, ready to coffe.   
grut, ready to coffe
  • enumerate
    index추가(0,1,2,3...)
for index, 변수 in enumerate(리스트(또는 튜플, 문자열)):
    수행할 문장1

while

  • 조건문이 참인 동안 계속반복
  • 안에 if문으로 break를 걸어줄 필요가 있을때도 있다.
while <조건문>:
    <수행할 문장1>
    <수행할 문장2>

continue,break

  • continue
    continue뒤부터 무엇을 하지않고 그냥 끝내는 것
  • break
    for문을 그 즉시 종료시킴
absent = [2,5]
no_book = [7]
for student in range(1,11):
    if student in absent:
        continue
    elif student in no_book:
        print("class is over, {0} follow the my room" .format(student))
        break
    print("{0}, read the book" .format(student))
출력결과
1, read the book
3, read the book
4, read the book
6, read the book
class is over, 7 follow the my room

한줄 for문

말 그대로 한줄로 표현한 for문이다. if문이 추가 될 수도있고, 중복 for문도 가능하다.

students = ["ironman","thor","groot"]
students = [i.upper() for i in students]

for i in range(2):
    if i==3:
        print(i)
    else :
        print("No")

[i if i==3 else "No" for i in range(2)]
출력결과
['IRONMAN', 'THOR', 'GROOT']
No
No
No
3
['No', 'No', 'No', 3]

0개의 댓글