2016-12-27 30 views
-1

何も入力せずに「Enter」を押しても問題ありません。それはエラーを示しています!有効な入力が与えられるまでユーザーに再度入力を求める方法はありますか?具体的には、「Enter」だけが押されたかどうかをユーザに再度問い合わせる。 Python:何も入力せずに「Enter」キーが押された場合に再度入力を求めます。

def dice(): 
user = input("Do you want to roll the dice? ") 
while user[0].lower() == 'y': 
    num = randrange(1, 7) 
    print("Number produced: ", num) 
    user = input("Do you want to roll the dice? ") 

ループが何度も何度もお聞きしますが、 "入力" を押すと、エラーを以下を

Do you want to roll the dice? 
Traceback (most recent call last): 
File "C:/Users/a/Documents/Code/Learning_Python/dice_rolling_simulator.py", line 12, in <module> 
dice() 
File "C:/Users/a/Documents/Code/Learning_Python/dice_rolling_simulator.py", line 6, in dice 
while user[0].lower() == 'y': 
IndexError: string index out of range 

答えて

0

whileの状態で使用user。これは、空の文字列がFalseに評価され、Pythonでブール演算子が(userFalseであるならば、user[0].lower() == 'y'は何IndexErrorが提起されませんので、評価されることはありません)短絡されていることをされている事実を利用しています:

while user and user[0].lower() == 'y': 
0

を示しています。

Xin = input("blah blah blah") 
while Xin == "": 
    Xin = input ('blah blah blah') 
0

はい..!可能です。

def dice(): 
    i = 1; 
    while i: 
     user = input("Do you want to roll the dice? ") 
     if user != None: 
      i = 0 

    while user[0].lower() == 'y': 
     num = randrange(1, 7) 
     print("Number produced: ", num) 
0

あなたはそれを言い換える必要があります。 ここにコメントとインポートのコード全体があります。

#importing random for randrange 

import random 

#defining rolling mechanism 

def dice(): 

    #looping so that you can keep doing this 
    while True: 
    #asking for input 
     user = input("Do you want to roll the dice? ") 
     #if the user says 'y': 
     if user.lower() == 'y': 
      #it picks a random number from 1 to 6 and prints. 
      num = random.randrange(1, 7) 
      print("Number produced: ", num) 
     #if not it will print that it doesn't understand the input and loop 
     else: 
      print("We don't understand your answer.") 
dice() 
関連する問題