Loop that adds user inputted numbers and breaks when user types “end”

前端 未结 4 1175
伪装坚强ぢ
伪装坚强ぢ 2021-01-27 17:23

Create a function that expects no arguments. The function asks user to enter a series of numbers greater than or equal to zero, one at a time. The user types end to indicate tha

4条回答
  •  暖寄归人
    2021-01-27 17:52

    Think about what your loop is checking for:

    "Do this, while the number is greater than or equal to 0 and it is not 'end'`.

    Which value satisfies both conditions? If I enter 'end' then does it satisfy both criteria; because your loop will only break if both conditions are true.

    So you really want or not and.

    Once you solve that issue, you'll run into another problem:

    >>> def sum_function():
    ...     number = 0
    ...     while number >= 0 or number is not 'end':
    ...         number = number + float(input('Enter a number: '))
    ...     return number
    ... 
    >>> sum_function()
    Enter a number: 1
    Enter a number: 3
    Enter a number: end
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 4, in sum_function
    ValueError: could not convert string to float: end
    

    The problem here is that you are converting everything to a float immediately after its entered; so as soon as someone enters 'end', your program crashes because it cannot convert 'end' to a float.

    Try to solve that one yourself :-)

提交回复
热议问题