Python🍍

Python 반복문 while, for⚡

Jeein0313 2022. 6. 27. 19:22

Python has two primitive loop commands:

  • While loops
  • For loops

 

1️⃣While Loops

With the while  loop we can execute a set of statements as long as a condition is true.

i=1;
while i<6:
	print(i);
    if i==3:
    	break;
    i+=1;

#1
#2
#3
i=0;
while i<6:
	i+=1
    if i==3:
    	continue;
    print(i)
 
#1
#2
#4
#5
#6
i=1;
while i<6:
	print(i)
    i+=1
else:
	print("i is no longer less than 6");

#1
#2
#3
#4
#5
#i is no longer less than 6

2️⃣For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.(이것은 다른 프로그래밍 언어의 for 키워드와 비슷하지 않으며 다른 객체 지향 프로그래밍 언어에서 볼 수 있는 반복자 메서드와 더 유사하게 작동합니다.)

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

my_list=[1,2,3,4]
my_tuple=(1,2,3,4)
my_dict={"ceo":"cindy","cfo":"james"}

for i in my_list:
	print(f"hi : {i}");

#hi : 1
#hi : 2
#hi : 3
#hi : 4

for key in my_dict:
	print(key);
#ceo
#cfo

for key in my_dict:
	print(my_dict[key]);
#cindy
#james

mylist=[('a','b'),('c','d'),('1','2')];
for item in mylist:
	print(item);
    
#('a', 'b')
#('c', 'd')
#('e', 'f')

for item1, item2 in mylist:
	print(item1);
    print(item2);
#a b
#c d
#e f

fruits=["apple", "banana", "cherry"]
for x in fruits:
    print(x)
    if x=="banana":
        break;
#apple 
#banana

for x in fruits:
    if x=="banana":
        continue
    print(x);
#apple
#cherry

for x in range(2,6,2):
    print(x); 
#2 
#4

for x in range(6):
    print(x)
else:
    print("Finally finished!");
#0
#1 
#2 
#3 
#4 
#5 
#Finally finished!

for x in range(6):
  if x == 3: break
  print(x)
else:
  print("Finally finished!")
#0 
#1 
#2 
#If the loop breaks, the else block is not executed.

'Python🍍' 카테고리의 다른 글

Python Lambda🍋  (0) 2022.06.27
Python Function✨  (0) 2022.06.27
Python 조건문 If🙄  (0) 2022.06.27
Python Operators👀  (0) 2022.06.25
Python Data Types💥  (0) 2022.06.25