【发布时间】:2018-11-05 01:07:26
【问题描述】:
我将参加我的第一个 Python 课程,并且与大多数 Python 课程一样,最后一项任务是创建一个 1-100 的猜谜游戏,以跟踪 VALID 尝试的次数。我无法获得(或在 stackoverflow 上找到)的元素是如何拒绝无效的用户输入。用户输入必须是整数,介于 1 和 100 之间的正数。我可以让系统拒绝除 0 和
我唯一能想到的就是告诉我不能让运算符比较字符串和整数。我一直想使用诸如guess > 0 和/或guess
# Generate random number
import random
x = random.randint(1,100)
# Prompt user for input
print("I'm thinking of a number from 1 to 100")
counter = 0
while True:
guess = input("Try to guess my number: ")
# Check if input is a positive integer and is not 0 or >=101
# this line doesn't actually stop it from being a valid guess and
# counting against the number of tries.
if guess == "0":
print(guess, "is not a valid guess")
if guess.isdigit() == False:
print(guess, "is not a valid guess")
else:
counter += 1
guess = int(guess)
# Begin playing
if guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
print(guess, "is correct! You guessed my number in", counter, "tries!")
【问题讨论】:
-
查看 Try 以及如果 try 失败如何处理。用户将传递一个单词,您尝试将其转换为 int,如果失败,则给出输入无效的输出。
-
int(guess)应该是第一件事。如果失败,则它不是整数。然后你只需要检查它是小于 1 还是大于 100,这很容易,因为它已经被转换为整数了。 -
与其单独考虑猜测无效的所有情况,不如尝试为猜测是否有效创建一个测试。
标签: python