2016-11-24 5 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() 

このコードを単純化して同じ機能を持たせる方法はありますか?クラスを使用せずに別のバージョンを試しましたが、 "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」または「no」と答えることによって明示的に要求することです。

したがって:

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!") 
関連する問題