![](/img/trans.png)
[英]How do i take user input from discord and store it as a variable to use in an equation? Discord.py
[英]How do I store a variable that has been created from a user input and use it in a different file in Python?
我是 Python 的新手,因此是 Stack Overflow 社區的新手。 我已經開始了我的第一個迷你項目,我想從一組 6 人中隨機生成一個團隊並分配兩個隨機團隊。 從那里我試圖創建兩個文件(每個團隊一個),每次一個用戶可以從他們的團隊中輸入每個玩家的分數,最終我希望它在單獨的文件中創建一個實時排行榜。 我已經成功創建了一個團隊生成器。 這是它的本質:
numberofplayers = int(len(online_players))
number_teams = int(input('How many teams do you want there to be?\n '))
k = int(numberofplayers/number_teams)
if numberofplayers == 6 and number_teams == 2:
global team_1
team_1 = random.sample(online_players, k)
str(team_1)
for x in team_1:
online_players.remove(x)
global team_2
team_2 = online_players
print('Team 1')
print(team_1[0] +'(1)')
print(team_1[1] + '(2)')
print('...')
print(team_1[2] +'(3)' +
'\n')
print('Team 2')
print(team_2[0] + '(4)')
print(team_2[1]+ '(5)')
print(team_2[2]+ '(6)')
這樣就成功生成了兩個 3 人的團隊。這個文件叫做 Team_Generator.py
在另一個名為 team_1_input.py 的文件中,我使用
from Team_Generator.py import team_1,team_2
print(team_1)
當我在控制台中運行它時,它會再次執行整個團隊生成器流程,而不僅僅是使用已分配的團隊表單 Team_Generator.py
關於如何讓它工作以便 team_1_input.py 識別從 Team_Generator.py 分配的團隊的任何見解?
謝謝
如果這段代碼也是你程序的起點,你應該在它周圍加上:
if __name__ == "__main__":
# your code here
它將阻止它在導入模塊時運行。
然而,通過導入你的主入口點,你創建了一個循環依賴:你的主文件依賴於另一個依賴於主文件的文件。 它可以工作,但它會讓你的生活變得不必要地復雜。
相反,您絕對應該讓您的其他文件公開一個將團隊作為參數的 function,並讓主文件調用它。
def do_something_about_teams(team_1, team_2):
print(team_1)
在你的主文件中:
from otherfile import do_something_about_teams
# beginning of main, etc...
do_something_about_teams(team_1, team_2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.