2016-11-24 51 views
0
import random 


def diceroll(): 
     num_dice = random.randint(1,6) 
     print("You got " + str(num_dice) + "!") 
diceroll() 
def question(): 
    response = input("You want to roll again?\n") 
     while response == "y": 
     diceroll() 
     response = input("You want to roll again?\n") 
    if response == "n": 
     print("Thank you for playing! :) ") 
     exit() 
    while "y" or "n" not in response: 
      response = input("Please answer with y or n!\n") 
      while response == "y": 
       diceroll() 
       response = input("You want to roll again?\n") 
      if response == "n": 
       print("Thank you for playing! :) ") 
       exit() 
question() 

有没有什么办法可以使这个代码更简单,并具有相同的功能?我tryed另一个版本不使用类,但一旦我进入另一个角色除了“Y”或“N”代码结束。我的第一个卷骰子蟒游戏

import random 

answer = "yes" 

while answer in ["yes", "y"]: 
    roll = random.randint(1,6) 
    print("You rolled " + str(roll) + "!") 
    answer = input("Would you like to roll again?\n") 
if answer in ["n", "no"]: 
    print("Thank you for playing!") 
else : 
    print("Please answer with yes or no!") 
    answer = input("Would you like to roll again?\n") 
+0

你的第一个版本不使用类。它正在使用一个功能 –

回答

0

你除了“Y”或“是”输入任何内容后,在程序退出的原因是因为这是你采取了什么为条件留在循环中。你的程序假设“呆在循环中”的意思是“玩游戏”,但是当有人输入非法输入时,他们也应该留在循环中。退出的唯一原因是通过回答“n”或“否”来明确要求。

这样:

import random 

while answer not in ["no", "n"]: 
    roll = random.randint(1, 6) 
    print("You rolled " + str(roll) + "!") 
    answer = input("Would you like to roll again?\n") 
    if answer not in ["yes", "y", "no", "n"]: 
     print("Please answer with yes or no!") 
     answer = input("Would you like to roll again?\n") 

print("Thank you for playing!")