I am new to learning python but I can't seem to find out how to make the first part of the while loop run in the background while the second part is running. Putting in the input I set allows the first part to run twice but then pauses it.
Here is the code
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()
Result:
Input: coins
1
Input: coins
2
Input:
My goal is to make the input print out 10 coins after 10 seconds, not 2 coins after two times of typing coins.
CodePudding user response:
What you are looking for is called Multithreading. Multithreading is a way to split your code up to a few separate units, that way one part can ask for the user input while the other is doing the calculation every second.
Working with Threads and multithreading in general is something that I'd consider intermediate level and not so much of a beginner level.
Here is a tutorial by Tutorialspoint about multithreading in Python if you want to get an over view on this subject.
CodePudding user response:
How about this.
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()
Output:
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