python - 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”,但不知道如何...
解决方案
guess = int(in.... 不要将其转换为 int,而是转换为字符串。
然后看看字符串是“q”还是“quit”
如果不是 q 或退出,则将其转换为 int : elif int(guess) < random_number:
推荐阅读
- encryption - 如何使用 Windows CryptoAPI 中的原始十六进制密钥值为 CryptDecrypt 创建对称密钥?
- if-statement - 析取 G1 ; G2 vs. If-then-else Cond -> G1 ; G2
- python - 通过该类的方法调用该类的参数的参数
- xml - 最小长度在下面的代码中不起作用。当我为 Name 提供空白值时,它通过了模式验证(它应该抛出错误)
- mysql - 如何修复“无法打开所需的默认文件:/usr/local/ampps/mysql/etc/my.cnf”错误?
- javascript - 在 JavaScript 中按下键时重复运行代码
- css - 如何使用响应式图像编写半垂直页面
- docker - 在 docker run 时执行一个 shell 脚本
- python - 如何让这个线性回归模型更准确,因为我得到了 5% 的准确度,这根本不可行?
- python - 如何制作存储自己答案的按钮?