2013-05-12 148 views
-2

我要檢查用戶輸入是否是一個數字,如果是繼續的代碼,如果它不將其重新詢問,直到他們進入一些檢查用戶輸入?

# This progam will simulate a dice with 4, 6 or 12 sides. 

import random 

def RollTheDice(): 

    print("Roll The Dice") 
    print() 




    ValidNumbers = [4,6,12] 

    Repeat = True 

    while Repeat == True: 
     Counter = 0 
     NumberOfSides = input("Please select a dice with 4, 6 or 12 sides") 

     if not type(NumberOfSides) == int or not int(NumberOfSides) == ValidNumbers: 
      print("You have entered an incorrect value") 
      NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides")) 


     else: 
      print() 
      UserScore = random.randint(1,NumberOfSides) 
      print("{0} sided dice thrown, score {1}".format (NumberOfSides,UserScore)) 

      RollAgain = input("Do you want to roll the dice again? ") 


      if RollAgain == "No" or RollAgain == "no": 
       print("Have a nice day") 
       Repeat = False 

      else: 
       NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: ")) 
+0

的Python 3的方式 – 2013-05-12 16:43:21

+2

相關:http://stackoverflow.com/questions/8114355/loop-until-a-specific-user-input – 2013-05-12 16:44:07

+0

你能給我答案嗎? – 2013-05-12 16:44:55

回答

0

首先,一般的編程習慣:使用駝峯或under_scores爲變量名稱。

這裏是(我覺得)你想:

validNumbers = [4, 6, 12] 
repeat = True 
while repeat: 
    userNum = input("Enter a number ") # input returns a string 
    try: # try to convert it to an integer 
     userNum = int(userNum) 
    except ValueError: 
     pass 
    if userNum in validNumbers: 
     repeat = False 
# do everything else 
+0

謝謝你喲它終於有效! – 2013-05-12 17:57:54