Loops and Branches (Cheat Sheet)
Loops and Branches (Cheat Sheet)if statement
if 9 > 5:
print(" 9 is great than 5")
print(" End of Program")
Two important things
- A colon":" is required after the condition
- Ident with at least one space
x = 1
y = 2
if x > y:
print(" x is larger")
else:
print(" x is not larger")
Important: The colon after the key word else!
number = 3
if number == 1:
print("one")
elif num == 2:
print("two")
elif num == 3:
print("three")
else:
print("something different")
while loop
i=1 while i<=5: i = i + 1 print(i)
infinite loops
i = 0
while True:
print(i)
if i >= 6
print("leave the loop"
break
print("Done...")
continue will end a block in a loop. It will force the program counter to jump back to the next test in the while condition
i = 0
while i<6:
i += 1
if i == 3:
print(" Will skip rest of block...")
continue
print(i)
for Loop
days =["Monday", " Tuesday", "Wednesday", "Thursday", " Friday", "Saturday", "Sunday"] for day in days: print(day +"!")
for loops can iterate over strings
str = "this is a string" count=0 for x in str: if(x == "t"): count += 1 print(count)
break and continue can be used in the for block
- 150 views