python新手问题
我按照视频编写了一段代码,感觉虽然跟视频里的效果差不多,但是有一个小毛病我想解决掉。设置输入不同的数字时,会显示相应的语句。 但是我如果不输入数字,而是直接打回车,就会出现一大串字符,这个要怎么解决?代码如下:
print("mulai")
temp = input("math")
yuan = int(temp)
import random
ai = random.randint(0,100)
while yuan != ai:
print("heart is busy")
temp = input("why")
yuan = int(temp)
if yuan >= ai:
print("what")
if yuan <= ai:
print("where")
print("forever")
直接回车的错误反馈如下:
Traceback (most recent call last):
File "D:\Python\Python38\1.py", line 3, in <module>
yuan = int(temp)
ValueError: invalid literal for int() with base 10: '' 本帖最后由 Jamesonwjt 于 2020-9-3 23:01 编辑
print("mulai")
temp = input("math")
while True:
try:
temp != '\n'
yuan = int(temp)
break
except:
temp = input("math")
import random
ai = random.randint(0,100)
print(ai)
while yuan != ai:
print("heart is busy")
temp = input("why")
yuan = int(temp)
if yuan >= ai:
print("what")
if yuan <= ai:
print("where")
print("forever")
我更新了一下我的代码,你可以再试试看,忘记加break 本帖最后由 1q23w31 于 2020-9-3 07:48 编辑
print("mulai")
temp = input("math:")
if temp=='':
print('输入错误')
else:
yuan = int(temp)
import random
ai = random.randint(0,100)
while yuan != ai:
print("heart is busy")
temp = input("why")
yuan = int(temp)
if yuan >= ai:
print("what")
if yuan <= ai:
print("where")
print("forever")
因为你直接回车,回车也算个字符。
但是回车不属于整数列,没法int化,导致出现值错误的提示。 heidern0612 发表于 2020-9-3 08:00
因为你直接回车,回车也算个字符。
但是回车不属于整数列,没法int化,导致出现值错误的提示。
input直接返回回车之前的字段、直接回车,就是个空字符串,不是回车 新手来看看 。{:10_269:}{:10_269:} Jamesonwjt 发表于 2020-9-3 07:33
希望是你想表达的意思
我试了一下你的代码,直接回车几次后还是有那个错误提示 heidern0612 发表于 2020-9-3 08:00
因为你直接回车,回车也算个字符。
但是回车不属于整数列,没法int化,导致出现值错误的提示。
那怎么解决这个问题呢? lzlwww021 发表于 2020-9-3 16:07
我试了一下你的代码,直接回车几次后还是有那个错误提示
我更新了,再试试看 Jamesonwjt 发表于 2020-9-3 23:02
我更新了,再试试看
可以了。请问一下,代码中的
while True:
try:
temp != '\n'
yuan = int(temp)
break
except:
temp = input("math")
这段是什么意思?为什么加了这段回车就不会报错了? lzlwww021 发表于 2020-9-4 00:57
可以了。请问一下,代码中的
while True:
try:
这个涉及到try和except的用法,也就是异常处理。具体的你可以去搜索一下他们的详细用法。 Jamesonwjt 发表于 2020-9-4 07:25
这个涉及到try和except的用法,也就是异常处理。具体的你可以去搜索一下他们的详细用法。
好的
页:
[1]