n = 5
while n > 0:
print(n)
n = n - 1
print('Blastoff!')
5
4
3
2
1
Blastoff!
Evaluate the condition, yielding True or False.
If the condition is false, exit the while statement and continue execution at the next statement.
If the condition is true, execute the body and then go back to step 1.
This type of flow is called a loop because the third step loops back around to the top.
We call each time we execute the body of the loop an iteration.
The body of the loop should change the value of one or more variables so that eventually the condition becomes false and the loop terminates.
If the loop repeats forever, it results in an infinite loop.
n = 10
while True:
print(n)
n = n - 1
print('Done!')
What will happen if you run this?
Ctrl+C to terminate it.
Finishing iterations with break
while True:
line = input('Please enter:')
if line == 'done':
break
print(line)
print('Done!')
Finishing iterations with continue
while True:
line = input('Please enter:')
if line == '#':
continue
if line == 'done':
break
print(line)
print('Done!')
numbers = [12,37,5,42,8,3]
even = []
odd = []
while len(numbers)>0:
x = numbers.pop()
if x%2==0:
even.append(x)
else:
odd.append(x)
print(even)
print(odd)
[8, 42, 12]
[3, 5, 37]
print("BMI指数计算器\n")
while True:
try:
inp_1 = input('请输入您的体重(kg):\n')
weight = float(inp_1)
break
except:
print('请输入数字')
while True:
try:
inp_2 = input('请输入您的身高(cm):\n')
height = float(inp_2)
break
except:
print('请输入数字')
a = int(input('Enter the 1st number:'))
b = int(input('Enter the 2nd number:'))
if a >= b:
x = a
y = b
else:
x = b
y = a
while y!=0:
r = y
y = x%y
x = r
print(x)
Least common multiple?
name_list=['a', 'b', 'c', 'd', 'e', 'f']
i=1
while len(name_list)>1:
if i%7==0:
y=name_list.pop()
else:
y=name_list.pop()
name_list.insert(0,y)
# print(name_list)
i=i+1
print(name_list)
i = 2
while i < 100:
j = 2
while j**2 <= i:
if i%j == 0 :
break
j = j + 1
if j**2 > i:
print(i)
i = i + 1
for statement works on the lists.
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends:
print('Happy New Year:', friend)
print('Done!')
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Done!
We call the while statement an indefinite loop because it simply loops until some condition becomes False, whereas the for loop is looping through a known set of items so it runs through as many iterations as there are items in the set.
In particular, friend is the iteration variable for the for loop. The variable friend changes for each iteration of the loop and controls when the for loop completes. The iteration variable steps successively through the three strings stored in the friends variable.
The concept of looping is important because it is one of the most common ways a computer automates repetitive tasks.
The indentation errors are common.
Python uses indentation to determine when one line of code is connected to the line above it. Some languages require the "end" statement.
Always indent the line after the for statement in a loop.
friends = ['Joseph', 'Glenn', 'Sally']
for x in friends:
print('Happy New Year:', x)
print('Done!')
IndentationError: expected an indented block
message = "Hello Python world!"
print(message)
IndentationError: unexpected indent
Forgetting to indent additional lines (logical error)
friends = ['Joseph', 'Glenn', 'Sally']
for x in friends:
print('Happy New Year:', x)
print('Looking forward to seeing you,', x)
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Looking forward to seeing you, Sally
friends = ['Joseph', 'Glenn', 'Sally']
for x in friends:
print('Happy New Year:', x)
print('Looking forward to seeing you,', x)
Happy New Year: Joseph
Looking forward to seeing you, Joseph
Happy New Year: Glenn
Looking forward to seeing you, Glenn
Happy New Year: Sally
Looking forward to seeing you, Sally
How to calculate 1+2+...+100?
First, we need to generate a series of numbers in a list.
for value in range(1,4):
print(value)
1
2
3
>>> type(range(1,5))
range
>>> list(range(1,6))
#list() creates an empty list.
[1, 2, 3, 4, 5]
>>> list(range(6))
[0, 1, 2, 3, 4, 5]
>>> list(range(1, 10, 2))
# make a list of odd numbers
[1, 3, 5, 7, 9]
>>> list(range(10, 1, -2))
[10, 8, 6, 4, 2]
1+2+3+...+100
total=0
for value in range(1,101):
total=value+total
print(total)
[2, 4, 6, 8, 10]
a list of square number
squares = []
for value in range(1,11):
square = value**2
squares.append(square)
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
count = 0
for x in [3, 41, 12, 9]:
count = count + 1
print('Count: ', count)
total = 0
for x in [3, 41, 12, 9]:
total = total + x
print('Total: ', total)
a_list=[3, 41, 12, 9, 74, 15]
largest = a_list[0]
for x in a_list:
if x > largest :
largest = x
print('Largest:', largest)
x = []
for i in range(1,4):
x.append([])
for j in range(1,4):
x[i-1].append(1)
print(x)
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
x = []
for i in range(1,4):
x.append([])
for j in range(1,i+1):
x[i-1].append(1)
print(x)
[[1], [1, 1], [1, 1, 1]]
for i in range(1,4):
for j in range(i):
print(i,end=" ")
print()
1
2 2
3 3 3
# reverse?
>>> print("hello",end="+")
hello+
for i in range(1,4):
for j in range(i):
print(i,end="+")
print()
1+
2+2+
3+3+3+