Continually prompting user for input in Python

前端 未结 7 2007
余生分开走
余生分开走 2021-01-16 16:22

Objective: * Write a python program that repeatedly prompts for input of a positive number until the sum of the numbers is greater than 179. Use at least three modules/fun

7条回答
  •  有刺的猬
    2021-01-16 17:15

    When you're writing a standalone Python program, it’s a good practice to use a main function. it allows you to easily add some unit tests, use your functions or classes from other modules (if you import them), etc.

    And as others already said, it is a good idea to create a list and append a new element to it each time the user enters a valid number (until the sum of the numbers axceeds 179). If user entered an incorrect value, then just don’t append anything to the list and skip to the next iteration (so the user will be asked to enter a number again).

    So basically it could look like this:

    def validate_entered_number(num):
        """
        Checks if the number is positive and is less or equal to 42.
        Returns True if the number matches these conditions,
        otherwise it returns False.
        """
        if num < 0:
            print "That is not a positive integer."
            return False
    
        if num > 42:
            print "The number cannot exceed 42."
            return False
    
        return True
    
    def main():
        entered_numbers = []
    
        while True:
            try:
                num = int(raw_input("Enter a positive integer less or equal to 42: "))
            except ValueError:
                print "You should enter a number"
                continue
            if validate_entered_number(num):
                entered_numbers.append(num)
                if sum(entered_numbers) > 179:
                    print "The sum of the numbers is %s" % sum(entered_numbers)
                    print "The smallest number entered is %s" % min(entered_numbers)
                    print "The largest number entered is %s" % max(entered_numbers)
                    return
    
    if __name__ == "__main__":
        main()
    

    In fact, I can imagine a situation where you would want to just store the sum of the numbers, the smallest number and the largest number in three variables and update these variables in each iteration (add current number to the sum and compare it to the currently known smallest and larger numbers and update the corresponding variables when necessary), but in this case the longest list you can possibly have is only 180 elements (if all numbers are 1 and the user doesn’t enter 0 or you have modified the program to deny entering 0), which is very small amount of elements for a list in Python. But if you had to deal with really big amounts of numbers, I’d recommend to switch to a solution like this.

提交回复
热议问题