首页 > 解决方案 > Python3:如何在需要整数的while循环中检查字符串

问题描述

在 Python3 中:如何在需要整数的 while 循环中检查字符串...

这是我目前的代码:我想用“quit”或“q”替换标记值“0”。我该怎么做?

import random

highest = 10
lowest = 1
counter = 0

random_number = random.randint(lowest, highest)
# The randint function is in the random function within the random MODULE imported above.

guess = int(input(f"Guess a number between {lowest} and {highest}. Enter '0' at any time to quit: "))

while guess is not random_number:
    if guess == 0:
        print("Quitting game.")
        break
    elif guess < random_number:
        counter += 1
        guess = int(input("Guess higher: "))
    elif guess > random_number:
        counter += 1
        guess = int(input("Guess lower: "))
    if guess == random_number:
        print(f"Correct! Well done!! You got it right after {counter} guess(es)!")

我想将标记值“0”更改为“q / quit”,但不知道如何...

标签: pythonstringwhile-loopintegersentinel

解决方案


guess = int(in.... 不要将其转换为 int,而是转换为字符串。

然后看看字符串是“q”还是“quit”

如果不是 q 或退出,则将其转换为 int : elif int(guess) < random_number:


推荐阅读