Everything works fine but if I press "Enter" without entering anything. It shows error! Is there any way to ask user to input again till a valid input is given. More specifically, to ask user input again if just "Enter" is pressed.
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? ")
When "Enter" is pressed, following error shows
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 Answers 4
While loop to ask again and again.
Xin = input("blah blah blah")
while Xin == "":
Xin = input ('blah blah blah')
Comments
Use user in the condition of the while. This takes advantage of the facts that empty strings are evaluated to False and that the boolean operators in Python are short-circuited (if user is False then user[0].lower() == 'y' won't be evaluated, hence no IndexError will be raised):
while user and user[0].lower() == 'y':
Comments
Yes..! it is possible.
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)
Comments
You need to rephrase it. Here's the whole code with comments and imports.
#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()