# 0813 Loops Benson Chiu @ FDCS 8th X 7th <!-- Put the link to this slide here so people can follow --> slide: https://hackmd.io/@benson-elementary-cpp/rJkf-SMet --- ## A brief example Input: An interger $n$ Output: A triangle of $n$ levels --- ## A straightforward approach ```python= n = int(input()) if n == 1: print("*") elif if n == 2: print("*\n**") ...... ``` Problem: Maybe n is 1000 or more, it's probably impossible to type that code in a short time --- ## Introduction: For loop ```python= for n in container: block ``` e.g. ```python= n = [0,1,2,3] for i in n: print(i) ``` --- ## range function - range(m,n) -> $[m,n)$ ```python= for i in range(0,10): print(i,end=" ") #0 1 2 3 4 5 6 7 8 9 ``` --- ## Break, continue - Break: leave the loop immediately - Continue: Skip to the beginning of the next loop ```python= for i in range(1,20): if i == 5: continue print(i,end=" ") if i == 10: break #1 2 3 4 6 7 8 9 10 ``` --- ## Multiple for loops A classic example: multiplication table ```python= for i in range(1,10): for j in range(1,10): print(i,"*",j,"=",i*j,end='\t') print("\n") ``` --- ![](https://i.imgur.com/IQbe1y2.png) --- ## Introduction: While loop ```python= while condition: codeblock ``` ![](https://i.imgur.com/SdZgdAG.png ) https://www.askpython.com/python/python-while-loop --- ```python= i = 1 while i <= 5: print(i,end=" ") i+=1 #1 2 3 4 5 ``` You can also use break and continue in while ```python= i = 1 while i <= 20: if i == 5: i+=1 continue if i == 10: break print(i,end=" ") i+=1 #1 2 3 4 6 7 8 9 ``` --- ## Back to the triangle problem ```python= n = int(input()) for i in range(0,n): for j in range(0,i+1): print("*",sep='',end='') print() ```
{"metaMigratedAt":"2023-06-16T07:05:59.137Z","metaMigratedFrom":"YAML","title":"0813 Loops","breaks":true,"description":"View the slide with \"Slide Mode\".","slideOptions":"{\"spotlight\":{\"enabled\":true}}","contributors":"[{\"id\":\"29625303-a0ab-4215-b54d-35c95f11006b\",\"add\":2398,\"del\":365}]"}
    275 views
   Owned this note