首页 > 解决方案 > Python:IDE中的代码是正确的,但在作业中是不正确的

问题描述

所以我正在做 Python 作业,我更喜欢在 IDE 中写作业的答案,然后复制并粘贴我的答案。对于这个特定的问题,我就是这样做的,虽然代码在 IDE 中运行良好,但在作业中被标记为不正确。

作业问题:编写一个从标准输入读取字符串的循环,其中字符串是“duck”或“goose”。读入“goose”时循环终止。循环之后,您的代码应打印出已读取的“duck”字符串的数量。

我的作业说: 检测到的问题:⇒ _stdout 的值不正确。

我的答案:

duckcount = 0
animal = ''
while True:
    animal = input('enter animal')
    if animal == 'duck':
        duckcount +=1
    elif animal == 'goose':
        break
print(duckcount)

该代码在我的 IDE 中运行良好,但我在作业中收到的错误消息是:_stdout 的值不正确。

标签: pythonpython-3.xwhile-loop

解决方案


我想知道您的老师是否由于您的输入字符串默认没有任何空格而在输入中添加了自己的空格。

尝试这个:

duckcount = 0
animal = ''
while True:
    animal = input('enter animal: ').strip()
    if animal == 'duck':
        duckcount += 1
    elif animal == 'goose':
        break

if duckcount == 1:
    print('There is {} duck!'.format(duckcount))
else:
    print('There are {} ducks!'.format(duckcount))

结果:

enter animal: duck   
enter animal:    duck
enter animal:  duck
enter animal: goose
There are 3 ducks!

推荐阅读