V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Laynooor
V2EX  ›  Python

新手请教 Python 这段代码有什么问题么?

  •  
  •   Laynooor · 2021-01-20 11:31:50 +08:00 · 1916 次点击
    这是一个创建于 1163 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我看来看去,横竖发现不了有什么问题,除了输入非数字的时候会报错?

    题目原文是 for certain series of integers...will not produce the correct output

    flag = False
    maxNumber = 0
    while not flag:
        print("请输入数字( 0 结束输入): ", end="")
        userInput = input()
        num = int(userInput)
        if num != 0:
            if num > maxNumber:
                maxNumber = num
        else:
            flag = True
    print(str(maxNumber))
    

    您是否可以看到,如果输入某些整数序列,它不会产生正确的输出? 在什么情况下它将无法正常工作?如何更改程序以使其正常工作? 您可以假定用户将在最后一个 0 之前输入至少一个非 0 的数字。

    第 1 条附言  ·  2021-01-20 13:35:08 +08:00
    中午脑子不清醒,负数其实我想到了,但实际程序跑了一遍,我输入-5,-10,0,然后输出 0,我一时竟觉得没什么问题...

    现在回头一想不对,0 是结束循环用的,不是输入值
    6 条回复    2021-01-29 17:24:19 +08:00
    engHacker
        1
    engHacker  
       2021-01-20 11:35:53 +08:00 via iPhone   ❤️ 2
    又来问作业了?
    imn1
        2
    imn1  
       2021-01-20 12:10:55 +08:00   ❤️ 1
    什么才算“正确的输出”?
    最后输出 0 不算正确么?那么全部输入负数,最后输入 0,print 就是 0
    溢出?
    JeffGe
        3
    JeffGe  
       2021-01-20 12:16:45 +08:00 via Android   ❤️ 1
    你试试输入 -5, -4, -3, -2, -1
    renmu123
        4
    renmu123  
       2021-01-20 12:24:10 +08:00 via Android   ❤️ 1
    flag 不需要,直接在 else 里 break 就可以了。
    输入负数有问题,可以把 maxnumber 初始值设置为负无穷。
    输入非数字报错。
    最后 str ()其实也没什么用。
    lizytalk
        5
    lizytalk  
       2021-01-20 13:59:20 +08:00   ❤️ 1
    负数就不对啊
    zixu01
        6
    zixu01  
       2021-01-29 17:24:19 +08:00
    maxNumber 值 默认值可以设成 None,

    ```
    if num > maxNumber:
    maxNumber = num
    ```
    之前,添加判断
    ```
    if maxNumber is None:
    maxNumber = num
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1061 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 19:04 · PVG 03:04 · LAX 12:04 · JFK 15:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.