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

前端 未结 4 1163
伪装坚强ぢ
伪装坚强ぢ 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:40

    you could use a try catch, if there is a Value Error when you are looking for a number they probably typed end, non the less you can do the apropriate checking in the except block.

    0 讨论(0)
  • 2021-01-27 17:45

    Split up the loop into more discrete steps:

    def SumFunction():
        """Sum of all values entered"""
        number = 0
        user_input = 1
        while user_input >= 0:
            user_input = input("Enter next number: ")
            if user_input == 'end':
                break
            user_input = float(user_input)
            number += max(user_input, 0)
        return number
    

    This first gets user input and checks if it's 'end'. If it is, the program breaks out of the loop and returns the running total, number. If it isn't, the program converts the user input to a number and adds it to number. If the number is 0 or negative, the program will add nothing to number, and the loop will stop. Finally, the resulting number is returned.

    0 讨论(0)
  • 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 "<stdin>", line 1, in <module>
      File "<stdin>", 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 :-)

    0 讨论(0)
  • 2021-01-27 17:58

    This program is what you want I guess:

    def SumFunction():
        sum = 0
        while(True):
            x = input('Enter: ')
            while x.lower()=='end':
                return sum
            while float(x) >= 0:
                sum += float(x)
                break
            else:
                print ("Wrong Number!")
    

    Output:

    >>> SumFunction()
    Enter: 1
    Enter: 2
    Enter: -1
    Wrong Number!
    Enter: end
    3.0
    >>> 
    

    You can use break in a loop to go out of it. You can also use return method to exit of a function. When you went out of a function, you also went out of the loop!

    The else block for a loop runs if and only if the loop is exited normally (i.e., without hitting a break).

    0 讨论(0)
提交回复
热议问题