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")
x = 1
y = 1
while x:
inp_1 = input('请输入您的体重(kg):\n')
try:
weight = float(inp_1)
x = 0
except:
print('请输入数字')
while y:
inp_2 = input('请输入您的身高(cm):\n')
try:
height = float(inp_2)
y = 0
except:
print('请输入数字')
BMI = weight/(height/100)**2
if BMI<18.5:
print("您的体型偏瘦")
elif BMI<24 and BMI>=18.5:
print("您的体型正常")
elif BMI<28 and BMI>=24:
print("您的体型偏胖")
elif BMI<32 and BMI>=28:
print("您的体型肥胖")
elif BMI>=32:
print("您的体型过于肥胖")
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
Now we answer the question. How to calculate 1+2+...+100?
First, we need to generate a series of numbers in a list.
for value in range(1,5):
print(value)
1
2
3
4
>>> type(range(1,5))
range
>>> numbers = list(range(1,6))
#list() creates an empty list.
>>> print(numbers)
[1, 2, 3, 4, 5]
>>> numbers = list(range(6))
>>> print(numbers)
[0, 1, 2, 3, 4, 5]
>>> numbers = list(range(1, 10, 2))
>>> print(numbers)
[1, 3, 5, 7, 9]
>>> numbers = list(range(10, 1, -2))
>>> print(numbers)
[10, 8, 6, 4, 2]
1+2+3+...+100
total=0
for value in range(1,101):
total=value+total
print(total)
Make a list of even numbers
even_numbers = list(range(2,11,2))
print(even_numbers)
[2, 4, 6, 8, 10]
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]
Example 1: len()
count = 0
for x in [3, 41, 12, 9]:
count = count + 1
print('Count: ', count)
Example 2: sum()
total = 0
for x in [3, 41, 12, 9]:
total = total + x
print('Total: ', total)
Example 3: max(), min()
largest = None
for x in [3, 41, 12, 9, 74, 15]:
if largest is None or x > largest :
largest = x
print('Largest:', largest)
Largest: 74
Example 4: .reverse()
reverselist = []
count = 0
x = [3, 41, 12, 9, 74, 15]
for itervar in x:
count = count + 1
for i in range(count-1, -1, -1):
reverselist.append(x[i])
print(reverselist)
[15, 74, 9, 12, 41, 3]
Sorting is a much more complicated and interesting topic.
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
>>> 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+
print("简易记账本（九月）")
September=[]
for date in range(20210901,20210931):
September.append([date])
print()
day=input("请问要输入几号的开销？")
print("请输入每一笔开销，结束请输入ok")
expense=[]
n=1
while n!=0:
each = input("第"+str(n)+"笔:")
if each == "ok":
n=0
else:
expense.append(float(each))
n=n+1
print("记录成功")
September[int(day)-1].append(sum(expense))
expense_total=0
for each_day in September:
if len(each_day) == 2:
expense_total = expense_total + each_day[1]
print()
print("本月支出汇总报告")
print("总支出：" + str(expense_total))
while True:
day=input("请问要输入几号的开销？如果结束请输入ok: ")
if day=="ok":
break
else:
# all the programs in Step 3
indentation: select programs, tab (or space)
cancel indentation: select programs, shift + tab
9月具体开支信息:
9-1 100
9-2 150