有人可以看看我的代码,并告诉我一些使我的代码更高效或更短的方法。我的程序基本上会生成1到6之间的2个数字并取它们的和。如果总和等于3,7,11,则程序会说“您赢了”。如果总和为奇数,则表示“您输了”。如果总和是偶数,则显示为“抽取”。最后,它显示获胜游戏的数量和获胜游戏的百分比。我该如何让它询问用户是否想再次发挥更高的效率呢(对python还是很新的)。谢谢
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)
您在其中重复相同的代码,if/elif
但一次只能执行一次。
您可以使用lower()
,然后不必与upper比较N
。您可以使用,strip()
因为有时人们会在答案中加空格而看不到。
您可以使用if total in (3, 7, 11):
。
可以使用类似的ie。if user in ('n', 'no', 'quit'):
lower_case
名称作为变量=
,==
,+=
,等代码:
import random
import time
random.seed(time.time())
games_played = 0
won = 0
print "DICE ROLLING GAME"
print
while True:
games_played += 1
num1 = random.randint(1, 6)
num2 = random.randint(1, 6)
total = num1 + num2
print "I just rolled %d and %d (total: %d)." % (num1, num2, total)
if total in (3, 7, 11):
print "You Win!"
won += 1
elif total % 2 == 1:
print "Lose!"
#elif total % 2 == 0:
else:
print "Draw"
print
answer = raw_input("Would you like to try again (y/n): ")
answer = answer.strip().lower()
if answer == "n":
break
print
print "You won %d out of %d games, or %.0f%%." % (won, games_played, (float(won) / games_played) * 100)
并使用一些随机值作为种子(即当前时间戳记),因为seed(1234)
它总是给出相同的结果。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句