Recently, I have been trying to learn python and now that I have covered most of the basics, I have started writing short basic programs in IDLE to test my knowledge as well as apply what I`ve learnt.
One of the programs I made simulates a dice roll. Here is the program below:
import random
response = input("Type \"roll\" to roll dice")
while response == "roll":
print(random.randint (1, 6))
input("Type \"roll\" to roll dice again or \"close\" to exit")
if response == "close":
break
For the most part, the program works. When you type "roll", you will be given a random number between 1-6. However, this only works the first time you input "roll". After the first initial input, any input from then on will give you a random number (e.g. typing "car", "dfgh", "dog", etc.).
This leads into the next problem I stumbled across, inputting "close" will also cause a random number to be generated (as if you typed "roll") and will not end the program as intended. It will only exit the program if "close" is the first initial input.
Any assistance would be greatly appreciated.
Kind regards,
lindon.
2 Answers 2
You have to assign the second input() to response variable:
import random
response = input("Type \"roll\" to roll dice")
while response == "roll":
print(random.randint (1, 6))
response = input("Type \"roll\" to roll dice again or \"close\" to exit")
if response == "close":
break
Comments
This is the right code. ####################
import random
response = input("Type \"roll\" to roll dice")
while response == "roll":
print(random.randint (1, 6))
response=input("Type \"roll\" to roll dice again or \"close\" to exit")
if response == "close":
break
########### Your are not take the input in response variable inside the while loop.