关于try语句
import randomsecret = random.randint(1,10)
times = 3
print("games")
print("输入数字",end = "")
guess = 0
while times != 0 and guess != secret:
try:
temp = input()
guess = int(temp)
times = times - 1
if guess == secret:
print("yes")
else:
if guess > secret:
print("big")
print("again",end = "")
else:
print("small")
print("again",end = "")
print("end")
except ValueError as reason:
print('哈哈出错了,值错误',str(reason))
这个语句运行的时候总是提醒我是不合语法的,但是我不知道为啥?应该是try的地方出了问题,可是问题在哪里呢? 你 cry 和 except 之间隔了那么多级缩进,当然没用! 从times = times - 1 到 print("end") 这几行同时增加一个缩进,这些都应该在try的里面 特点是博爱 发表于 2022-3-24 13:50
从times = times - 1 到 print("end") 这几行同时增加一个缩进,这些都应该在try的里面
import random
secret = random.randint(1,10)
times = 3
print("games")
print("输入数字",end = "")
guess = 0
while times != 0 and guess != secret:
try:
temp = input()
guess = int(temp)
times = times - 1
if guess == secret:
print("yes")
else:
if guess > secret:
print("big")
print("again",end = "")
else:
print("small")
print("again",end = "")
print("end")
except ValueError as reason:
print('哈哈出错了,值错误',str(reason))
这样也不行,提示print('end')这里有语法错误,如果print("end")单独再缩进的话,没有语法错误了,但是程序就不能达成原先的目标了 python爱好者. 发表于 2022-3-24 13:45
你 cry 和 except 之间隔了那么多级缩进,当然没用!
try和except必须紧密相连吗,
我来类比一下
if ***:
***
print('***')
elif***:
***
这里的elif还能执行吗 Jerry~Mouse 发表于 2022-3-24 14:02
try和except必须紧密相连吗,
我来类比一下
if ***:
对呀,你这样写 if else 也是错误的! python爱好者. 发表于 2022-3-24 14:21
对呀,你这样写 if else 也是错误的!
好的 明白了 谢谢解答
页:
[1]