for <<variable>> in <<list>>:
<<block>>
for num in range(3):
print(num)
0
1
2
py
코드를 입력하세요
fruit = ['apple', 'banana', 'cherry']
count = [3, 4, 1]
for i in range( len(fruit) ):
print( fruit[i], ':', count[i] )
apple : 3
banana : 4
cherry : 1
>>> a = range(3)
>>> list(a)
[0,1,2]
positive = ['Li', 'Na']
negetive = ['F', 'Cl']
for metal in positive:
for halogen in negative:
print( metal + halogen )
LiF
LiCl
NaF
NaCl
while <<expression>>:
<<block>>
# 사용자의 이름을 입력받으면 이름을 불러 인사하는 프로그램
text=""
while text != "quit":
text = input("Please enter your name(or "quit" to exit) : ")
if text == "quit":
print("exiting programs..")
else:
print("hello", text)
# 문자열에서 숫자의 위치를 출력하는 프로그램
a = 'C3H7'
digit_index = -1
for i in range(len(a)):
if a[i].isdigit():
digit_index = i
1
break로 인해 반복문이 3을 실행하고 멈췄기 때문에 7의 위치는 출력되지않음
a = 'C3H7'
total = 0 # 문자열 속 숫자의 합
count = 0 # 문자열 속 숫자의 개수
for i in range(len(a)):
if a[i].isalpha():
continue #a[i]가 문자라면 뒤의 부분을 실행하지 않음
total = total + int(a[i])
count = count + 1
print('total:',total)
print('count:',count)
10
2