【问题标题】:Cant make the first part of the while loop run indefinitely无法使 while 循环的第一部分无限期运行
【发布时间】:2022-01-05 22:21:29
【问题描述】:

我是学习 python 的新手,但我似乎不知道如何让 while 循环的第一部分在后台运行,而第二部分正在运行。输入我设置的输入允许第一部分运行两次,然后暂停。

这里是代码

import time

def money():

    coins = 0
    multiplyer = 1
    cps = 1

    while True:
        coins = coins + cps
        time.sleep(1)
    
        player_input = input("Input: ")
        if player_input == "coins":
            print(coins)
            player_input

    money()

结果:

    Input: coins
    1
    Input: coins
    2
    Input: 

我的目标是让输入在 10 秒后打印出 10 个硬币,而不是在两次输入硬币后打印出 2 个硬币。

【问题讨论】:

  • 代码中的cps是什么?

标签: python while-loop do-while


【解决方案1】:

您正在寻找的是所谓的多线程。多线程是一种将代码拆分为几个单独单元的方法,这样一部分可以要求用户输入,而另一部分每秒都在进行计算。

一般来说,使用线程和多线程是我认为的中级水平,而不是初学者水平。

Here is a tutorial by Tutorialspoint 关于 Python 中的多线程,如果您想全面了解这个主题。

【讨论】:

    【解决方案2】:

    这个怎么样。

    import time
    
    
    def money():
    
        coins = 0
        multiplyer = 1
        cps = 1
    
        while True:
            coins = coins + cps
    
            # Print coins when it reaches 10.
            if coins == 10:
                print(f'coins: {coins}')
                break  # get out of while loop
    
            time.sleep(1)
    
            while True:    
                player_input = input("Input: ")
                if player_input == "coins":
                    break  # goto the first while loop and add single coin to coins
                
                # If player input is not 'coins' we ask again.
                print('input again')
                    
    
    money()
    

    输出:

    Input: z
    input again
    Input: coins
    Input: coin
    input again
    Input: coins
    Input: coins
    Input: coins
    Input: coins
    Input: coins
    Input: coins
    Input: coins
    Input: coins
    coins: 10
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 2014-10-05
      • 2021-05-06
      • 2015-06-25
      • 2014-01-30
      • 2014-03-29
      相关资源
      最近更新 更多