python - 当用户仅单击输入时,我试图停止循环?

标签 python python-3.x

当用户输入数字 <=0 或用户仅单击输入时,我试图停止此循环。 当用户仅单击输入时如何创建中断?

    number = int(input('Type a number, [to stop type 0 or less]'))
    num_sum = number
    times = 0

    while True:
        number = int(input('Type a number, [to stop type 0 or less]'))
        num_sum += number
        times += 1
        if number <= 0:
            break

    average = num_sum / times
    print(f'{times} number received \nThe average of number recceived is:'+'{:.4f}'.format(average))

最佳答案

input()int() 作为两个单独的步骤调用。

while True:
    # call input() by itself, without calling int()
    answer = input('Type a number, [to stop type 0 or less]')

    # if the user pressed enter without typing an answer, break
    if not answer:
        break

    # otherwise convert answer to an integer
    number = int(answer)

    # remaining code is unchanged

关于python - 当用户仅单击输入时,我试图停止循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59994760/

相关文章:

python - 在 Python 3.5 中用花括号将字符串解析为数组

python - 从字典的完整笛卡尔积创建数据框

python-3.x - 如何使用 python 3.8 获取 AWS S3 对象位置/URL?

python - 您如何知道新列表是已创建还是刚刚修改?

python - 从 HTML 中提取标签和属性 - 困难的方法

python - 管理多个 settings.py 文件

python - 使用 python 和 http.client 在发布请求中包含证书的示例

python - 使用 numpy 进行乘法累加

python - 为什么在这个 if 语句中调用变量会给我一个语法错误。我在这里缺少什么规则?

python - 如何在 python 中安装 xml.dom.minidom