Почему мой код не позволяет мне l oop определенной части кода, а зацикливание всего кода? - PullRequest
1 голос
/ 06 марта 2020

Итак, в настоящее время я создаю игру для небольшого биржевого брокера, используя python для моего задания, и я столкнулся с проблемой. Мой следующий урок не раньше вторника на следующей неделе, и я не могу найти какие-либо хорошие решения для моей проблемы. По сути, этот код предназначен для первоначального уменьшения времени на 1 каждый раз, когда игрок решает подождать день, однако время остается равным 20, независимо от того, сколько раз игрок ждет. Я также не уверен, как сделать так, чтобы мой код зацикливал раздел ввода пользователя: «Вы хотели покупать акции, продавать акции или ждать день?» Пока пользователь не скажет, что хотел бы подождать. Есть ли исправление для этой проблемы, и если да, то что это? Вот код, о котором я говорю:

stocks = 0
time = 21
money = 100
print("You have $" + str(money) + " in your bank.")  
while time > 0:
    stock = random.randint(1,20)
    time = time - 1
    while True:        
        print("You have " + str(time) + " days remaining until the market closes")
        print("Stocks are currently worth: $" + str(stock)) 
        choice = input("Did you want to buy stocks, sell stocks or wait a day?  ")
        if choice.casefold() == "buy":       
            while True:
                numberBuy = int(input("Enter the number of stocks that you would like to buy:  "))
                if numberBuy * stock > money:
                    print("You don't have the money for that")
                else:
                    break
            money = money - (numberBuy * stock)
            stocks = stocks + numberBuy
            print("You bought " + str(numberBuy) + " stocks and you spent $" + str(numberBuy * stock) + " buying them. You now have $" + str(money) + " and you have " + str(stocks) + " stocks")
        elif choice.casefold() == "sell":
            while True:
                numberSell = int(input("Enter the number of stocks that you would like to sell:  "))
                if numberSell > stocks:
                    print("You don't have enough stocks for that. You have " + str(stocks) + " stocks and you want to sell " + str(numberSell))
                else:
                    break
            stocks = stocks - numberSell
            money = money + (numberSell * stock)
            print("You sold " + str(numberSell) + " stocks and you made $" + str(numberSell * stock) + " selling them. You now have $" + str(money) + " and you have " + str(stocks) + " stocks")
        elif choice.casefold() == "wait" or "wait a day" or "wait day":
            print("You wait for the next day to come. At the end of the day, you have $" + str(money) + " in your bank account and you have " + str(stocks) + " stocks to")
            print("your name")
            print(" ")
            print("===========================================================================================================")
            print(" ")```  


1 Ответ

0 голосов
/ 06 марта 2020

Причина, по которой time никогда не меняется, заключается в том, что весь код, основанный на выборе пользователя, находится в секунде, а l oop, который в настоящее время не имеет формы выхода. Быстрое решение состоит в том, чтобы переместить строку time = time - 1 в соответствующую опцию в операторе if. Также я думаю, что вы должны удалить второе время, пока l oop полностью, потому что цена акций никогда не изменится.

while time > 0:
    stock = random.randint(1,20)
    print("You have " + str(time) + " days remaining until the market closes")
    print("Stocks are currently worth: $" + str(stock)) 
    choice = input("Did you want to buy stocks, sell stocks or wait a day?  ")
    if choice.casefold() == "buy":       
        while True:
            numberBuy = int(input("Enter the number of stocks that you would like to buy:  "))
            if numberBuy * stock > money:
                print("You don't have the money for that")
            else:
                break
        money = money - (numberBuy * stock)
        stocks = stocks + numberBuy
        print("You bought " + str(numberBuy) + " stocks and you spent $" + str(numberBuy * stock) + " buying them. You now have $" + str(money) + " and you have " + str(stocks) + " stocks")
    elif choice.casefold() == "sell":
        while True:
            numberSell = int(input("Enter the number of stocks that you would like to sell:  "))
            if numberSell > stocks:
                print("You don't have enough stocks for that. You have " + str(stocks) + " stocks and you want to sell " + str(numberSell))
            else:
                break
        stocks = stocks - numberSell
        money = money + (numberSell * stock)
        print("You sold " + str(numberSell) + " stocks and you made $" + str(numberSell * stock) + " selling them. You now have $" + str(money) + " and you have " + str(stocks) + " stocks")
    elif choice.casefold() == "wait" or "wait a day" or "wait day":
        time = time - 1
        print("You wait for the next day to come. At the end of the day, you have $" + str(money) + " in your bank account and you have " + str(stocks) + " stocks to")
        print("your name")
        print(" ")
        print("===========================================================================================================")
        print(" ")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...