Könnte jemand meinen Code ansehen und mir einige Möglichkeiten nennen, wie ich meinen Code effizienter oder kürzer machen könnte? Mein Programm erzeugt grundsätzlich 2 Zahlen zwischen 1 und 6 und nimmt deren Summe. Wenn die Summe gleich 3,7,11 ist, sagt das Programm "Sie haben gewonnen". Wenn die Summe eine ungerade Zahl ist, heißt es "du verlierst". Und wenn die Summe eine gerade Zahl ist, steht "draw". Zuletzt wird die Anzahl der gewonnenen Spiele und der Prozentsatz der gewonnenen Spiele angezeigt. Wie kann ich den Teil machen, an dem der Benutzer gefragt wird, ob er wieder effizienter spielen möchte (immer noch neu bei Python). DankWie kann ich meinen Python-Code in Bezug auf While-Schleifen verbessern?
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)
zuerst Leerzeichen um '=', '==', '+ =' hinzufügen, um es lesbarer zu machen Verwenden Sie 'lower_case' Namen für Variablen. Wir verwenden 'CamelCase'-Namen für Klassen. Finden Sie 'PEP8' Dokument über Python-Code-Formatierung. – furas
Sie können 'wenn total in (3, 7, 11)' und verwenden Sie 'user = user.lower()', so dass Sie nicht brauchen Benutzer == "N", etc. – furas
in Sie Code 'elif. .. continue' ist nutzlos. Es funktioniert auf die gleiche Weise ohne "weiter" – furas