0

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
asked Dec 27, 2016 at 7:57

4 Answers 4

1

While loop to ask again and again.

Xin = input("blah blah blah")
while Xin == "":
 Xin = input ('blah blah blah')
answered Dec 27, 2016 at 8:01
Sign up to request clarification or add additional context in comments.

Comments

0

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':
answered Dec 27, 2016 at 8:02

Comments

0

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)
answered Dec 27, 2016 at 8:09

Comments

0

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()
answered Dec 27, 2016 at 8:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.