Tải bản đầy đủ (.pdf) (2 trang)

038 while loop tủ tài liệu training

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (394.83 KB, 2 trang )

while loop
While loops, like the For loops, are used for repeating specific block of codes. The "while" loop is capable of anything that
the "for" loop can do. But unlike a for loop, the while loop will not run n times, but until a defined condition is no longer met.
If the condition is initially false, the loop body will not be executed at all.
The syntax of this loop is:
while (condition):
statement_1
statement_2
...
...
statement_n

Let's make our examples;
In [1]: count = 0
while (count < 10):
print ('The count is:',count)
count += 1
print("It's done!")
The count is:
The count is:
The count is:
The count is:
The count is:
The count is:
The count is:
The count is:
The count is:
The count is:
It's done!

0


1
2
3
4
5
6
7
8
9

In [2]: a = 1
while (a < 10):
print (a)
a+= 2
1
3
5
7
9

The Complete Python 3 Programming Course: (Beginner to Advanced)


In [3]: n = 10
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1
# update counter

# print the sum
print("The sum is", sum)
The sum is 55

In [5]: i=0
text="Python is great!"
while iprint(text[i],text)
i+=1
P
y
t
h
o
n
i
s
g
r
e
a
t
!

Python
Python
Python
Python
Python
Python

Python
Python
Python
Python
Python
Python
Python
Python
Python
Python

is
is
is
is
is
is
is
is
is
is
is
is
is
is
is
is

great!
great!

great!
great!
great!
great!
great!
great!
great!
great!
great!
great!
great!
great!
great!
great!

Infinite Loop
Since we don't increase i variable, it will become an infinite loop. Please do not run this code!
In [ ]: i=0
while (i<15):
print(i)

This is the end of this lesson.
See you in our next lessons.
In [ ]:

The Complete Python 3 Programming Course: (Beginner to Advanced)




×