提问人:Knight Gamer650 提问时间:10/21/2023 最后编辑:philipxyKnight Gamer650 更新时间:10/21/2023 访问量:52
我怎样才能使Python while循环仅在只有一个条件为真的情况下继续?[复制]
How can I make a Python while loop continue only if exactly one condtition is true? [duplicate]
问:
如果我写 ,则仅当一个语句为真时,循环才应继续,但当两个条件为真时,就像我使用逻辑运算符一样。如果我写 ,那么当一个条件为真时,它就会运行。or
and
and
我希望它在 while 循环中只有一个条件为真时运行。
我该如何解决这个错误?
import random
def game():
import random
answer = random.randint(1, 100)
print('Welcome to the Number Guessing Game!')
print('I am thinking of a number between 1 and 100.')
print(f'Pssst, the correct answer is {answer}.')
diff = input('Choose a difficulty. Type e for easy h for hard:\n ')
lives = 10
if diff == 'h':
lives = 5
end = 0
while end == 0 or lives != 0:
print(f'You have {lives} attempts remaining to guess the number.')
guess = int(input('Make a guess: '))
if guess > answer:
lives -= 1
print("Too high.")
if guess < answer:
lives -= 1
print('Too low.')
if guess == answer:
print(f'You got it! The answer was {answer}.')
end = 1
答:
-1赞
Irony-Bearheart
10/21/2023
#1
也许您想保持循环运行,当且仅当 中只有 1 且正好为 1 True 时。试试这个: 或 .
提示:对于一个对象,当且仅当 将为 False。否则将是.[end == 0, lives != 0]
while (end == 0 and lives == 0) or (end != 0 and lives != 0)
bool(end) is bool(lives)
int
i
i == 0
bool(i)
True
评论
while end == 0 or lives != 0
当 时停止。决定何时停止。然后循环播放。PS De Morgan 定律说是 .PS:要记录某事是否如此,请使用布尔值。end != 0 and lives == 0
while not
!(x one_of_AND_or_OR y)
!x the_other_one !y