第五课课后习题动手题
改进小游戏,提醒用户输入错误格式import random
times = 3
secret = random.randint(1,10)
print('Welcome!!!!!!')
guess = 0
print("Guess what number do I think?", end = " ")
while (guess != secret) and (times > 0):
guess = int(input())
while type(guess) != type(1):#应该是这里出问题了
print("Illegal type!")
times = times - 1
if guess == secret:
print("Bingo!")
print("Huh, without prize!")
else:
if guess > secret:
print("Too big!")
else:
print("Too small!")
if times > 0:
print("Try again!")
else:
print("You are out of chance!")
print("Game over!") 你的思路是错的,guess = int(input()) 这一句已经将 guess 转化为 int() 了,如果用户不输入整数会直接报错。
而且判断一个字符串可不可以强制转化为整数,需要使用字符串的 isdigit() 方法。
代码帮你改了:
import random
times = 3
secret = random.randint(1, 10)
print('Welcome!!!!!!')
guess = 0
print("Guess what number do I think?", end=" ")
while (guess != secret) and (times > 0):
guess = input()
while not guess.isdigit():
guess = input("Illegal type! Please input: ")
times = times - 1
if guess == secret:
print("Bingo!")
print("Huh, without prize!")
else:
if guess > secret:
print("Too big!")
else:
print("Too small!")
if times > 0:
print("Try again!")
else:
print("You are out of chance!")
print("Game over!") zltzlt 发表于 2020-3-7 21:57
你的思路是错的,guess = int(input()) 这一句已经将 guess 转化为 int() 了,如果用户不输入整数会直接报 ...
我知道了,但是如果这样写guess = input("Illegal type! Please input: ") guess的赋值就改变了,再重新输入其他数就会报错 Easier 发表于 2020-3-7 22:11
我知道了,但是如果这样写 guess的赋值就改变了,再重新输入其他数就会报错
这样试试:
import random
times = 3
secret = random.randint(1, 10)
print('Welcome!!!!!!')
guess = 0
print("Guess what number do I think?", end=" ")
while (guess != secret) and (times > 0):
guess = input()
while not guess.isdigit():
guess = input("Illegal type! Please input: ")
guess = int(guess)
times = times - 1
if guess == secret:
print("Bingo!")
print("Huh, without prize!")
else:
if guess > secret:
print("Too big!")
else:
print("Too small!")
if times > 0:
print("Try again!")
else:
print("You are out of chance!")
print("Game over!") zltzlt 发表于 2020-3-7 22:12
这样试试:
懂了,谢谢大佬
页:
[1]