Python:要求再次输入"输入"按下键而不输入任何内容

时间:2016-12-27 07:57:36

标签: python

一切正常但如果我按下#34;输入"没有输入什么。它显示错误!是否有任何方法要求用户再次输入,直到给出有效输入。更具体地说,如果仅仅输入"再次询问用户输入。被按下了。

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

4 个答案:

答案 0 :(得分:0)

while循环一次又一次地问。

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

答案 1 :(得分:0)

user的条件下使用while。这利用了空字符串被评估为False并且Python中的布尔运算符被短路的事实(如果userFalse然后user[0].lower() == 'y'赢了&#39 ; t被评估,因此不会引发IndexError

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

答案 2 :(得分: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)

答案 3 :(得分: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()