Created for
while
loop
while condition :
block
break
statement (discussed further)
i = 1
while i<=5 :
print(i)
i += 1
1
2
3
4
5
If you run next code, your Python will run an endless loop. Use CTRL+C or CTRL+Z to stop it
# print the numbers from 10 to 1:
i = 10
while i>=1 :
print(i)
i = 1
i = 1
sum = 0
while i <= 100:
sum += i
i += 1
print("sum = ", sum)
sum = 5050
sum = 2550
for
loop
for item in sequence :
#do something with item
for
statement is different than the "C-based" for
in other popular languages (C#, Java, PHP, JavaScript)for
statement iterates over the items of any sequence.foreach
loop concept in above-mentioned languages Iterate over symbols in string:
for s in "ada":
print(s.capitalize())
A
D
A
Iterate over list of numbers:
for num in [1,2,3,4]:
print(num)
1
2
3
4
for i in [1,2,3]:
for j in "abv":
print(j)
print("\n") #prints new line
for
statement will be shown in Sequence data types theme!break
statement
while condition:
block 1
if break_cond:
break # loop is terminated, block 2 is skipped
block 2
for item in sequence :
block 1
if break_cond:
break # loop is terminated, block 2 is skipped
block 2
str = "alibaba"
for s in str:
if s == "i": break
print(s)
a
l
do-while
emulation with break
while True:
user_number = int(input("Enter a positive number: "))
if user_number > 0:
break
print("Nice, your number is: ", user_number
do-while
emulation without break
user_number = int(input("Enter a positive number: "))
while user_number <= 0:
user_number = int(input("Enter a positive number: "))
print("Nice, your number is: ", user_number)
Can you imagine how the code would look like, if the "do" block was more than 1 line long?
Enter your user name (at least 3 symbols):
*** At least 3 symbols, please! Try again.
Enter your user name (at least 3 symbols): iv
*** At least 3 symbols, please! Try again.
Enter your user name (at least 3 symbols): iva
Nice, your user_name is: iva
continue
statement
while condition:
block 1
if continue_cond:
continue # go to while condition
block 2
for i in [1,2,3,4,5]:
if i == 3:
continue
print(i)
1
2
4
5
str = "alabala"
for s in str:
if s in ["a", "e", "i", "o", "u", "y"]:
continue
print(s)
l
b
l
These slides are based on
customised version of
framework