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

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

提交回复
热议问题