Как решить проблему с a для l oop in python? - PullRequest
0 голосов
/ 14 июля 2020

Я посылаю своего садовника собирать яблоки с дерева. Я даю ему 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
################################################

Почему?

Ответы [ 2 ]

1 голос
/ 14 июля 2020

Здесь:

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 >= 5 и if y <=5. Если y равно 5, оба условия удовлетворяются, и поэтому оба блока будут инициированы. Вы можете исправить это, изменив >= на > или <= на <. Или измените второй if на elif.

0 голосов
/ 14 июля 2020

Вы допустили опечатку. Во втором случае l oop у вас срабатывают оба условия, когда 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') 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...