04. loop structure

Loop structure

Scenarios

If we need to repeat the procedure to execute a command or some such program to control the robot to play football, if not yet entered the robot ball and shooting range, then we will have been issued instructions to let the robot run to the goal direction. Of course, you may have noticed, there is not only in describing just need to repeat the action, also need to use the previous chapter talking about branching structure. Cite a simple example, we want to achieve a 1 second printed once "hello, world" on the screen and print a sustained program every hour, we certainly can not directly put print('hello, world')this code to write 3600 times, if we really to do so, the programming work is too boring boring. Therefore, we also need to look at the structure of the cycle, with cyclic structure we can easily control something or some things repeat, repeat, repeat the execution.

Python is configured in a cyclic structure, there are two approaches, one is for-incircular, one is whilecirculating.

for-in loop

If you know exactly the number of cycles performed on a container or to iterate (will be mentioned later), then we recommend the use of for-incycle, for example, 1 to 100 sums calculation results in the following code ( n = 1 100 n \displaystyle \sum \limits_{n=1}^{100}n )。

"""
用for循环实现1~100求和

Version: 0.1
Author: 骆昊
"""

sum = 0
for x in range(101):
    sum += x
print(sum)

Note that the above code range(101)can be used to construct a range from 0 to 100, can be constructed so that a sequence of integer cycles and used, for example:

  • range(101)It may generate a sequence of integers 0 to 100.
  • range(1, 100)It may generate a sequence of integers 1 to 99.
  • range(1, 100, 2)It may generate a sequence of odd-numbered 1 to 99, wherein the step size is 2, i.e., the value of the incremental sequence.

Knowing this, we can use the following code to achieve the even sum between 1 and 100.

"""
用for循环实现1~100之间的偶数求和

Version: 0.1
Author: 骆昊
"""

sum = 0
for x in range(2, 101, 2):
    sum += x
print(sum)

May be realized using the same functionality as a branched structure through the loop, the code shown below.

"""
用for循环实现1~100之间的偶数求和

Version: 0.1
Author: 骆昊
"""

sum = 0
for x in range(1, 101):
    if x % 2 == 0:
        sum += x
print(sum)

while loop

If you do not know the structure loop structure specific number of cycles, we recommend the use whilecycle. whileA loop can be generated by transform an boolexpression of the values of the cycle, the value of the expression Truecycle continues, expression is Falseterminated. Here we (the computer a random number between 1 and 100, enter the number of people own guess, the computer gives prompt information corresponding to guess until people out of the digital computer) through a "Guess" mini-games to see look at how to use the whileloop.

"""
猜数字游戏
计算机出一个1~100之间的随机数由人来猜
计算机根据人猜的数字分别给出提示大一点/小一点/猜对了

Version: 0.1
Author: 骆昊
"""

import random

answer = random.randint(1, 100)
counter = 0
while True:
    counter += 1
    number = int(input('请输入: '))
    if number < answer:
        print('大一点')
    elif number > answer:
        print('小一点')
    else:
        print('恭喜你猜对了!')
        break
print('你总共猜了%d次' % counter)
if counter > 7:
    print('你的智商余额明显不足')

The above code uses the breakkeyword to terminate the loop early, important to note that breakonly terminate the cycle in which it is, which is using a nested loop structure (will be mentioned below) requires attention. In addition break, there are another key is continuethat it can be used to give up this cycle subsequent code directly recycled into the next round.

Branch structure and the same, but also can be nested loop structure, that may also be configured in the circulation loop structure. The following example demonstrates how to output the multiplication table by a nested loop.

"""
输出乘法口诀表(九九表)

Version: 0.1
Author: 骆昊
"""

for i in range(1, 10):
    for j in range(1, i + 1):
        print('%d*%d=%d' % (i, j, i * j), end='\t')
    print()

Exercise

Exercise 1: Analyzing enter a positive integer is not a prime number.

Tip : prime number, and refers to only be an integer greater than 1 divided by 1 itself.

Answer:

"""
输入一个正整数判断它是不是素数

Version: 0.1
Author: 骆昊
Date: 2018-03-01
"""
from math import sqrt

num = int(input('请输入一个正整数: '))
end = int(sqrt(num))
is_prime = True
for x in range(2, end + 1):
    if num % x == 0:
        is_prime = False
        break
if is_prime and num != 1:
    print('%d是素数' % num)
else:
    print('%d不是素数' % num)

Exercise 2: Enter two positive integers, and the least common multiple of the greatest common divisor calculation thereof.

Answer:

"""
输入两个正整数计算它们的最大公约数和最小公倍数

Version: 0.1
Author: 骆昊
Date: 2018-03-01
"""

x = int(input('x = '))
y = int(input('y = '))
# 如果x大于y就交换x和y的值
if x > y:
    # 通过下面的操作将y的值赋给x, 将x的值赋给y
    x, y = y, x
# 从两个数中较的数开始做递减的循环
for factor in range(x, 0, -1):
    if x % factor == 0 and y % factor == 0:
        print('%d和%d的最大公约数是%d' % (x, y, factor))
        print('%d和%d的最小公倍数是%d' % (x, y, x * y // factor))
        break

Exercise 3: printing a triangular pattern as shown below.

*
**
***
****
*****
    *
   **
  ***
 ****
*****
    *
   ***
  *****
 *******
*********

Answer:

"""
打印三角形图案

Version: 0.1
Author: 骆昊
"""

row = int(input('请输入行数: '))
for i in range(row):
    for _ in range(i + 1):
        print('*', end='')
    print()


for i in range(row):
    for j in range(row):
        if j < row - i - 1:
            print(' ', end='')
        else:
            print('*', end='')
    print()

for i in range(row):
    for _ in range(row - i - 1):
        print(' ', end='')
    for _ in range(2 * i + 1):
        print('*', end='')
    print()

I welcome the attention of the public number, reply keyword " Python ", there will be a gift both hands! ! ! I wish you a successful interview ! ! !

Published 95 original articles · won praise 0 · Views 3073

Guess you like

Origin blog.csdn.net/weixin_41818794/article/details/104243609