Python: program branching, use of loop structure

Everyone has a perceptual understanding of the branching and looping structures in Python. The importance of the branch and loop structure is self-evident, it is the basis for constructing program logic, and it is also a relatively difficult part for beginners. Most beginners can understand their purpose and usage after learning the branch and loop structures, but they can't start when encountering practical problems;

It is easy to understand other people's code, but it is very difficult to write the same code yourself. If you have the same problem and confusion, don't be depressed, it's just because you have just started your programming journey, and your practice volume has not yet reached the level that allows you to write code as you like, as long as you strengthen your programming practice, this problem Sooner or later it will be resolved. Below we will explain some classic cases for you.

Classic small case

Example 1: Finding the number of daffodils.

Explanation: Narcissus number is also known as super-complete number invariant number, narcissistic number, self-power number, Armstrong number, it is a 3-digit number, and the sum of the cubes of the numbers on each digit of the number is exactly equal to itself, for example :

The key to this topic is to split a three-digit number into ones, tens, and hundreds. This is actually very easy to do by using the // (division) and % (modulus) operators in Python. The code is as follows Show.

"""
找出所有水仙花数
"""
for num in range(100, 1000):
    low = num % 10
    mid = num // 10 % 10
    high = num // 100
    if num == low ** 3 + mid ** 3 + high ** 3:
        print(num)

The above trick of using // and % to split a number is still very commonly used when writing code. We want to invert a positive integer that does not know how many digits it has, such as changing 12345 to 54321, which can also be realized by using these two operations, the code is as follows.

"""
正整数的反转
"""
num = int(input('num = '))
reversed_num = 0
while num > 0:
    reversed_num = reversed_num * 10 + num % 10
    num //= 10
print(reversed_num)

Example 2: Hundreds of money and a hundred chickens problem.

Explanation: One hundred coins and one hundred chickens is a mathematical problem proposed by Zhang Qiujian, an ancient mathematician in my country, in the book "Suan Jing": one chicken is worth five, one hen is worth three, and three chickens are worth one. If you buy a hundred chickens for a hundred dollars, how much are the rooster, hen mother, and chicks? Translated into modern language is: 5 yuan for a rooster, 3 yuan for a hen, and 3 chicks for 1 yuan. If you buy 100 chickens for 100 yuan, how many roosters, hens, and chicks are there?

"""
《百钱百鸡》问题
"""
# 假设公鸡的数量为x,x的取值范围是0到20
for x in range(0, 21):
    # 假设母鸡的数量为y,y的取值范围是0到33
    for y in range(0, 34):
        z = 100 - x - y
        if 5 * x + 3 * y + z // 3 == 100 and z % 3 == 0:
            print(f'公鸡: {x}只, 母鸡: {y}只, 小鸡: {z}只')

The method used above is called the exhaustive method, also known as the violent search method. This method enumerates all possible candidates in the alternative solution one by one and checks whether each candidate matches the description of the problem, and finally gets solution to the problem. This approach may seem clumsy, but it is usually a viable or even a good choice for very powerful computers that can find a solution to a problem as long as it exists.

Example 3: CRAPS game.

Description: CRAPS, also known as craps, is a very popular table game in Las Vegas, USA. The game uses two dice, and the player gets points by shaking the two dice to play the game. The simplified rules are: if the player rolls the dice for the first time and gets 7 or 11 points, the player wins; if the player rolls 2 points, 3 points or 12 points for the first time, the dealer wins; if the player rolls other points Then the player continues to roll the dice, if the player rolls out 7 points, the banker wins; if the player rolls out the first number of points, the player wins; players with other points continue to roll the dice until the winner is determined.

"""
Craps游戏
我们设定游戏开始时玩家有1000元
游戏结束的条件是玩家破产(输光所有的)
"""
from random import randint

money = 1000
while money > 0:
    print(f'你的总资产为: {money}元')
    go_on = False
    # 下注金额必须大于0小于等于玩家总资产
    while True:
        debt = int(input('请下注: '))
        if 0 < debt <= money:
            break
    # 第一次摇色子
    # 用1到6均匀分布的随机数模拟摇色子得到的点数
    first = randint(1, 6) + randint(1, 6)
    print(f'\n玩家摇出了{first}点')
    if first == 7 or first == 11:
        print('玩家胜!\n')
        money += debt
    elif first == 2 or first == 3 or first == 12:
        print('庄家胜!\n')
        money -= debt
    else:
        go_on = True
    # 第一次摇色子没有分出胜负游戏继续
    while go_on:
        go_on = False
        current = randint(1, 6) + randint(1, 6)
        print(f'玩家摇出了{current}点')
        if current == 7:
            print('庄家胜!\n')
            money -= debt
        elif current == first:
            print('玩家胜!\n')
            money += debt
        else:
            go_on = True
print('你破产了, 游戏结束!')

Example 4: Fibonacci sequence.

Explanation: Fibonacci sequence (Fibonacci sequence), also known as the golden section sequence, is an ideal assumption condition studied by Italian mathematician Leonardo Fibonacci (Leonardoda Fibonacci) in "The Book of Calculation". The sequence introduced by the rabbit growth rate problem, so this sequence is often called "rabbit sequence". The characteristic of the Fibonacci sequence is that the first two numbers of the sequence are 1, and starting from the third number, each number is the sum of the previous two numbers. According to this rule, the first 10 numbers of the Fibonacci sequence The numbers are: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55. The Fibonacci sequence has direct applications in modern physics, quasi-crystal structure, chemistry and other fields.

"""
输出斐波那契数列前20个数
"""
# 前两个数都是1
a, b = 1, 1
print(a, b, end=' ')
# 通过递推公式算出后面的18个数
for _ in range(18):
    a, b = b, a + b
    print(b, end=' ')

Example 5: Print prime numbers.

Explanation: A prime number refers to a positive integer (excluding 1) that can only be divisible by 1 and itself.

"""
输出100以内的素数
"""
for num in range(2, 100):
    # 假设num是素数
    is_prime = True
    # 在2到num-1之间找num的因子
    for factor in range(2, num):
        # 如果找到了num的因子,num就不是素数
        if num % factor == 0:
            is_prime = False
            break
    # 如果布尔值为True在num是素数
    if is_prime:
        print(num)

The simple summary is still the same sentence: branch structure and loop structure are very important, they are the basis of constructing program logic, and a lot of practice must be done to achieve mastery. The example of the CRAPS game just mentioned can be used as a standard. If you can successfully complete this code, then you have mastered the knowledge of branch and loop structures.

Guess you like

Origin blog.csdn.net/y1282037271/article/details/129241796