# Dice Rolling Random Number and Guessing Game
import random
user_choice = 'y'
while user_choice != 'N' or user_choice != 'n':
print(random.randint(1,6))
user_choice = input("Do you want to continue: ")
print("You are exited")
CodePudding user response:
The logic of the while condition is wrong.
Your loop runs forever, because the character will ALWAYS be different from one of the suggested characters. So the while condition is always true as at least one of the two parts is always true.
You want something like
while user_choice != 'N' and user_choice != 'n':
...
If you want to go for a more 'pythonic' way, query a set in the while condition:
while user_choice not in {'n', 'N'}:
....
There are many similar ways with tuples, lists, ... to express the condition other than querying every character individually in a chain of 'and' conditions.
CodePudding user response:
As far as coding is concerned, the question is answered already, but I'd like to offer a more deep explanation of why the answer was the and
operation instead of or
.
The question "Did the user enter neither 'n'
or 'N'
?" can be expressed using Boole Algebra as
Answer = Not(
'n'
or'N'
), and using the DeMorgan theorem this can be rewritten asAnswer = Not(
'n'
) and Not('N'
)
In your code, the first of the two ways to write this would look like
while !(user_choice == 'N' or user_choice == 'n'):
I hope this clears up the logic behind your question.