0
有人可以看看我的代碼,並告訴我一些方法可以使我的代碼更有效或更短。我的程序基本上生成1到6之間的2個數字並且獲得它們的總和。如果總和等於3,7,11,程序會說「你贏了」。如果總數是一個奇數,它會說「你輸了」。如果總數是偶數,則表示「繪製」。最後顯示贏得的比賽數量和贏得比賽的比例。如何讓用戶如果想再次發揮更高的效率,我該如何製作這部分?(仍然是python的新手)。謝謝我該如何改進我的python代碼while while循環
import random
random.seed(1234)
GamesPlayed=0
Won=0
print "DICE ROLLING GAME"
print
while True:
#generates 2 numbers from 1 to 6
num1=random.randint(1,6)
num2=random.randint(1,6)
total=num1+num2
#This part checks to see if that total is equal to 3,7, or 11. it will say you win
if total==3 or total==7 or total==11:
print "I just rolled %d and %d." % (num1, num2)
GamesPlayed+=1
Won+=1
print "You Win!"
print
#next part ask user if they would like to play again
user=raw_input("Would you like to try again (y/n): ")
if user=="N" or user=="n":
break
elif user=="Y" or user=="y":
continue
#next part checks to see if the two random numbers are odd numbers, if so, it displays "you lose"
elif total % 2==1:
print "I just rolled %d and %d." % (num1, num2)
print "Lose!"
GamesPlayed+=1
print
#ask if the user would want to go again
user=raw_input("Would you like to try again (y/n): ")
if user=="N" or user=="n":
break
elif user=="Y" or user=="y":
continue
#If the total is an even number, it say "draw"
elif total % 2==0:
print "I just rolled %d and %d." % (num1, num2)
print "Draw"
GamesPlayed+=1
print
user=raw_input("Would you like to try again (y/n): ")
if user=="N" or user=="n":
break
elif user=="Y" or user=="y":
continue
#displays how many games the user won out of the number of games they played, also displays the percentage of the amount they won
print "You won %d out of %d games, or %.0f%%." % (Won, GamesPlayed, (float(Won)/GamesPlayed) * 100)
首先在'=','==','+ ='周圍增加空格,使其更具可讀性對變量使用'lower_case'名稱。我們使用'CamelCase'名稱作爲類。查找關於Python代碼格式的「PEP8」文檔。 – furas
你可以在(3,7,11)中總共使用'user = user.lower()',這樣你就不需要'user =='N「'等等。」 – furas
你代碼中'elif。 ..繼續'是無用的。它將以同樣的方式工作,而不用全部「繼續」 – furas