我(一個初學者)試圖創建一個 python 程式來為游戲捕獲 olympus 增加一個團隊的積分,這是我的整個程式
# initialise variables
player_names = []
player_scores = []
total = 0
points = 0
top_score = 0
score_valid = False
# main program
# opening message
print("welcome to capturing olympus point counter! begin by entering your team name.\n")
# get team name
team_name = input("\nteam name: ")
# prompt to enter player names
print("\nokay " team_name ", enter each of your 6 players names.\n")
# loop to create list of players names
for x in range(6):
name = input("enter the name of player " str(x 1) ": ")
player_names.append(name)
# loop for players to input their scores
for x in range(6):
while score_valid == False:
score_input = input("\n" str(player_names[x]) ", enter the number of hits you scored: ")
if type(int(score_input)) == int:
score_valid = True
score = int(score_input)
player_scores.append(score)
else:
print("try again.")
score_valid = False
# calculate total loop
for x in range(6):
total = player_scores[x]
# find average
average = round(float(total / 6), 2)
# find points
if total > 50:
points = 1
if average >= 10.00:
points = 1
# blank space
print("")
# results
if points == 1:
print("well done " team_name ", you earned a point!")
elif points == 2:
print("WOW! " team_name ", you earned 2 points!")
elif points == 0:
print("you earned 0 points. better luck next time!")
# find top score
for each_score in player_scores:
if each_score > top_score:
top_score = each_score
# find top scorer
i = player_scores.index(top_score)
top_scorer = player_names[i]
print("your top scorer was " top_scorer ", with " str(top_score) " points!")
在用戶輸入分數的部分,我試圖創建一個回圈,以便如果用戶沒有輸入整數,它會再次提示它們。
# loop for players to input their scores
for x in range(6):
while score_valid == False:
score_input = input("\n" str(player_names[x]) ", enter the number of hits you scored: ")
if type(int(score_input)) == int:
score_valid = True
score = int(score_input)
player_scores.append(score)
else:
print("try again.")
score_valid = False
我嘗試了很多不同的方法來測驗輸入是否為整數,這是代碼能夠運行通過這些行的唯一方法,但隨后進入本節:
# calculate total loop
for x in range(6):
total = player_scores[x]
并給我錯誤:
IndexError:串列索引超出范圍
如果我洗掉我檢查的部分我不會收到任何錯誤我不知道如何解決這個問題,謝謝你的幫助。
uj5u.com熱心網友回復:
player_scores你通過陳述句構建player_scores.append(score)。那么,player_scores你的回圈之后的大小是多少?我認為 len(player_scores) 并不總是 == 6,因為您通過while score_valid == False:. 成功輸入一個玩家的資料后,該變數score_valid不會為下一個玩家重置,而是保留為。FalseTrue
您可能需要從
# loop for players to input their scores
for x in range(6):
while score_valid == False:
...
至
# loop for players to input their scores
for x in range(6):
score_valid = False
while score_valid == False:
....
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515885.html
標籤:Python列表循环整数
下一篇:序列串列的子序列化
