-1
我想跟蹤變量TOTAL_TRI
。 TOTAL_TRI
包含遊戲中正確回答的問題的數量。當調用statistics
時,我需要保存該值並將其傳遞給函數statistics
。從本質上講,玩家將玩遊戲py_game
,TOTAL_TRI
將保存他們得到的問題的數量,當玩家調用功能statistics
時,它會顯示他們正確答案的數量?我一直在玩弄這一段時間,但沒有取得重大進展。有任何想法嗎?如何跟蹤python中的全局變量
P.S. 菜單中的其他遊戲尚未實現,但它們將執行相同的遊戲 - 保存正確數量的問題 - 並讓玩家撥打statistics
種類的東西。
在使用全局變量更新,企圖:
#py_game------------------------------------------------------------------------
import random
from random import choice
from random import randint
TOTAL_TRI = 0
def py_game():
for k in range (1,2):
print('\nPractice Problem', k, 'of 2')
min_pyramid_size = 3
max_pyramid_size = 5
total_chars = 0
num_rows = random.randint(min_pyramid_size, max_pyramid_size)
for i in range(num_rows):
x = ''.join(str(random.choice('*%')) for j in range(2*i+1))
print(' ' * (num_rows - i) + x)
total_chars = total_chars + x.count('%')
try:
user_answer = int(input('Enter the number of % characters' + \
' in the pyramid: '))
except:
user_answer = print()
if user_answer == total_chars:
print('You are correct!')
else:
print("Sorry that's not the correct answer")
points = 0
global TOTAL_TRI
for k in range (1,2):
print('\nProblem', k, 'of 10')
min_pyramid_size = 3
max_pyramid_size = 5
total_chars = 0
num_rows = random.randint(min_pyramid_size, max_pyramid_size)
for i in range(num_rows):
x = ''.join(str(random.choice('*%')) for j in range(2*i+1))
print(' ' * (num_rows - i) + x)
total_chars = total_chars + x.count('%')
try:
user_answer = int(input('Enter the number of % characters' + \
' in the pyramid: '))
except:
user_answer = print()
if user_answer == total_chars:
print('You are correct!')
points +=1
else:
print("Sorry that's not the correct answer")
TOTAL_TRI = points
#------------------------------------------------------------------------------
def statistics(points):
print('\nPyramid Game---------------------------')
incorrect = 10 - (points)
print ('You answered', points, 'questions correctly')
print ('You answered', incorrect, 'questions incorrectly')
#Main Menu--------------------------------------------------------------------------
def main_menu():
calculation_game = print("Enter 1 for the game 'Calculation'")
bin_reader = print("Enter 2 for the game 'Binary Reader'")
trifacto_game = print("Enter 3 for the game 'Trifacto'")
statistics = print("Enter 4 to view your statistics")
display_data = print("Enter 5 to display data")
save_game = print("Enter 5 to save your progress")
user_input = int(input('Make your selection: '))
if user_input == 1:
calculation()
if user_input == 2:
binary_reader()
if user_input == 3:
py_game()
if user_input == 4:
statistics(TOTAL_TRI)
if user_input == 5:
save_game()
if user_input != 1 or 2 or 3 or 4 or 5:
print('invalid input')
print('\n')
main_menu()
main_menu()
我嘗試了你所說的,但我只是收回語法錯誤。你知道我做錯了什麼嗎?我會發布更新。 – kjf545
你可以發佈你收到的錯誤嗎?全局聲明應該在函數的頂部進行。 –
對,我把它移到了函數的頂部,錯誤消失了。但是現在,當我運行代碼時,TOTAL_TRI的值不會被更改。實際上,py_game函數甚至不承認TOTAL_TRI的存在。我通過這個步進器進行驗證:http://www.pythontutor.com/visualize.html#mode=edit。 – kjf545