Study Notes Day09] [Python 2.7 branch and cycle three

1. While cycle

While 条件:
    循环体    

The condition is true the loop body has been executed, knowing the condition is false, exit the loop
the loop body can set conditions will change, it will after the execution of a certain cycle, will exit occurs, python can not execute an infinite loop

2. For cycle (cycle counter)

#python cycle and c language for loop is not the same, to be a bit more powerful functions
Example:

for 目标 in 表达式:
    循环体
favorite = "weivid"
for i in favorite:
    print(i,end=" ") # 打印字符串中的每个字符,并空格连接

Operating results, separated by spaces:
Here Insert Picture Description
Example II:

member = ['weivid', 'wangwei', 'yijing'] #[]定义member是一个列表类型
for each in member:
    print(each, len(each)) #len表示字符串的长度

operation result:
Here Insert Picture Description

3. range () and the like for loop

3.1 range () Method
Range ([Strat,], STOP [, STEP = 1])
#BIF has three parameters, wherein the [] represents the two parameters are optional
#step = 1 default third parameter represents value. 1
Range BIF this effect is to generate a parameter value from the start, to stop the end of the parameter value starts sequence of numbers

range(5) #返回一个range(0,5),值为0,1,2,3,4不包含5
#左闭右开[0,5)
print(range(5))

list1 = list(range(5))#list()把参数生成一个列表
print(list1)#输出[0,1,2,3,4]

The result:
Here Insert Picture Description
3.2 range pass a parameter from the default 0, start

print("传递一个参数的range(5)")
for i in range(5):
    print(i, end=" ")
print()

The result:
Here Insert Picture Description
3.2 range pass two parameters

print("#传递两个参数的range(1,10):")
for j in range(1, 10):
    print(j, end=" ")
print()

Run Results:
Here Insert Picture Description
3.3 range passed three parameters, the third parameter is the step

print("#传递三个5参数的range(1,10,2)")
for m in range(1,10,2):
    print(m, end=" ")
print()

operation result:
Here Insert Picture Description

4. Two key statements

1) break statement

Terminate the current cycle, out of the loop body
#break when the conditions are met can jump out of the loop

string = "I love weivid"
answer = input("请输入weivid最想听到的一句话:")

while True:
   if answer == string:
       break
   else:
       answer = input("sorry!请重新输入(答案对了才能退出):")

print("you are goood!")
2) continue Statement

Termination of the current round of cycle, the next round of the cycle, before executing the next cycle, first determine the conditions in execution, if not correct, then exit the loop

#continue
for i in range(10):
    if i%2 != 0:
        print(i)
        continue
    i += 2
    print(i)

Direct Print # odd number, and exits the loop, and another cycle begins
# even-if condition is not satisfied, then add 2 Printing
Run Results:
Here Insert Picture Description

5. Exercises

1. The following code fragment of how many times the printing
for i in range(0,10,2):
    print("I love weivid")

Five #

for j in 5:
    print("I love weivid!!!")

# Will complain, because in membership operator is

2. range (10) What will be the number?

Generates Range (0,10)
List (Range (0,10)) into a list [0,1,2,3,4,5,6,7,8,9], not included 10

3. What will the code fragment print? #break only one out of circulation
while True:
    while True:
        break
        print(1)
    print(2)
    break
print(3)

operation result:
Here Insert Picture Description

3. Under what circumstances, we need the loop body is always true?

Games for implementation, the operating system running servers.
Although never is True, but for the "death cycle", is not necessarily a bad thing, you can always use break out of the cycle

4. Society improve the efficiency of the code, modify the code fragment
i = 0
string = "I love weivid"
while i < len(string):
    print(i)
    i += 1

The reason why the above code fragment # inefficient, because: every cycle should use the function len ()
# modified as follows:

i = 0
string = "I love weivid"
length = len(string)
while i < length:
    print(i)
   i += 1
The programming problem

A program designed to validate the user password, the user only three chances to make a mistake, but if the content input includes
"*" then the number is not counted

count = 3
password = "I love weivid"  #假设密码设定为:I love weivid

while count > 0:
    answer = input("请输入用户密码:")
    if answer == password:
        print("密码正确,请进入程序")
        break
    elif '*' in password:
        print("密码不包含”*“号,请重新输入,您还有",count,"次机会!",end=" ")
        continue
    else:
        print("您的密码输入错误!您还有",count-1,"次机会!")
    count -= 1
6. Write a program, find the number of all daffodils between 100-999

If a three-digit number and is equal to the cube of the digits, this number is called narcissus, e.g. 153 = 1 . 3 + 5 . 3 + 3 . 3

for i in range(100,999):
    sumdata = 0
    temp = i
    while temp:
       sumdata = sumdata +  (temp%10)**3
       temp //= 10      # 此循环是计算每个数的三位数的立方和,注意使用地板除法
    if sumdata == i:
        print(i)
7. tri-color ball problem

Red, yellow and blue balls, three of which red, yellow 3, 6 blue, these balls into the box 12, the balls 8 from any work out, calculate various programming ball colour match

print("三色球:红、黄、蓝")
#red = yellow = blue = 0


for red in range(0,4):
    for yellow in range(0,4):
        for blue in range(2,7):
            if red + yellow + blue == 8:
                print(red,yellow,blue)
                
print("进程结束")    
Published 105 original articles · won praise 71 · views 40000 +

Guess you like

Origin blog.csdn.net/vivid117/article/details/104296118