繁体   English   中英

如何解决 python 中的 for 循环问题?

[英]How to solve problem with a for loop in python?

我派我的园丁从树上摘一些苹果。 我给了他 3 次尝试接红苹果和 2 次接绿色苹果的尝试。 他应该重复这个过程4次。

问题:为什么他有时要抓3次青苹果?

import random

def garden():
        green_apple = 0
        red_apple = 0
        tree = 50
        for _ in range(4):
            for _ in range(3):
                x = random.randint(1,10)
                if x >= 7:
                    tree -= 1
                    print('You catch an red apple! There are ' + str(tree) + ' apples left on the tree')
                    red_apple += 1
                if x <= 6:
                    print('No red apples this time')
            for _ in range (2): 
                y = random.randint(1,10)   
                if y >= 5:
                    tree -= 1
                    print('You catch an green apple! There are ' + str(tree) + ' apples left on the tree')
                    green_apple += 1
                if y <=5:
                    print('No green apples this time')    

        print('################################################')  
        return (red_apple, green_apple)

green_bag, red_bag = [], []

for _ in range(3):
    green_apple, red_apple = garden()
    green_bag.append(green_apple)
    red_bag.append(red_apple)

print(red_bag)
print(green_bag)


样本:

You catch an green apple! There are 39 apples left on the tree
You catch an green apple! There are 38 apples left on the tree
No green apples this time
################################################

为什么?

这里:

if y >= 5:
    tree -= 1
    print('You catch an green apple! There are ' + str(tree) + ' apples left on the tree')
    green_apple += 1
if y <=5:
    print('No green apples this time')

你有if y >= 5if y <=5 如果y等于5则两个条件都满足,因此,两个块都将被启动。 您可以通过将>=更改为><=更改为<来修复它。 或者,将第二个if更改为elif

你打错了。 在第二个 for 循环中,当 y==5 时触发了这两个条件。 你抓到一个青苹果,但在相同的 y 值下也没有抓到一个青苹果。

您可以在那里执行 if-else 块,或执行 elif 语句,这样两者就不会在相同的输入上执行。

for _ in range (2): 
            y = random.randint(1,10)   
            if y >= 5:
                tree -= 1
                print('You catch an green apple! There are ' + str(tree) + ' apples left on the tree')
                green_apple += 1
            else:
                print('No green apples this time') 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM