Continually prompting user for input in Python

前端 未结 7 2025
余生分开走
余生分开走 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 16:59

    Yes, of course there's a better way than making a variable for each number. Store them in a list. Storing them in a list also makes finding their sum and the highest and lowest value easy (there are built-in functions for this).

    As a further hint, you'll want to use two loops, one inside the other. The outer loop keeps the user entering numbers until their sum exceeds 179. The inner loop keeps the user entering a single number until it's between 1 and 42 inclusive.

    0 讨论(0)
  • 2021-01-16 17:00

    Thanks to everyone who answered. I've written the following code and it works nearly perfectly except the last module. If you exit the program after the first run (by pressing 0) it will exit, but if you run it a second time pressing 0 won't make it exit. It'll just go back to the beginning of the program. I don't know why.

    Note: The assignment has various requirements that I had to incorporate in my code. Hence the unnecessary modules, global variables, and comments.

    maxNum = 42  # declares global variable maxNum
    target = 179  # declares global variable target
    
    def user_input():  # prompts user to input a number 42 or less until all add up to 179
        x = 0
        nums = []    
        while sum(nums) <= target:
            nums.append(int(raw_input("Enter a number: ")))
            if int(nums[x]) > int(maxNum):
                print "Number cannot exceed 42."
                user_input()
            else:
                x += 1
        print_nums(nums,x)
    
    def print_nums(nums,x):  # prints the sum of the numbers, the smallest, and the largest 
        print "Sum of all numbers is", sum(nums)
        nums.sort()
        x -= 1
        print "Largest number entered is", nums[x]
        print "Smallest number entered is", nums[0]
        decide()
    
    def decide():  # allows user to continue the program or exit 
        exit = raw_input("<9 to enter a new set of number.  0 to exit.> ")
        while True:
            if int(exit) == 0:
                return
            elif int(exit) == 9:
                user_input()
    
    user_input()
    
    0 讨论(0)
  • 2021-01-16 17:10
    def get_int(prompt=''):
        while True:
            try:
                return int(raw_input(prompt))
            except ValueError:
                pass
    
    def get_values():
        values = []
        total  = 0
        while total <= 179:
            val = get_int('Enter a positive integer <= 42: ')
            if 0 <= val <= 42:
                values.append(val)
                total += val
        return values
    
    def print_info(values):
        print 'Sum is {}'.format(sum(values))
        print 'Largest value is {}'.format(max(values))
        print 'Smallest value is {}'.format(min(values))
    
    def main():
        values = get_values()
        print_info(values)
    
    if __name__=="__main__":
        main()
    
    0 讨论(0)
  • 2021-01-16 17:15

    You can knock out all three function requirements by encapsulating each step of your program. Rather than having your loop inside of a function, we'll let main control the loop, and we'll control the flow by passing data into and out of function calls.

    Let's rework your input_numbers() function a bit.

    def get_input_number():
        num = int(raw_input("Enter a positive integer no greater than 42 "))
        if num <= 0 or num > 42:
            print "Invalid input.  Try again "
            get_input_number()
        else: 
            return num
    

    So, instead of having input_numbers control the loop as well as the input handling and validation, we have it do just what its name implies: It asks for input, validates it, and then, if it's good, it returns the value to the caller, but if it's bad, it writes a message, and calls itself again to the user can enter good input.

    The next function we'll set up is straight from your list of requirements. From all of the numbers that the user enters, we need to find the biggest one. From the language alone, we can determine that we're looking through a set of numbers, and thus, this is a good place to break out a list. Assuming we store all of the users input in a list, we can then pass that list to a function and perform operations on it, like so.

    def get_greatest_number(input_list):
        highest = input_list[0]
        for i in input_list:
            if i > highest:
                highest = i
        return highest
    

    We set the first element of the list to a variable highest and then check all other elements in the list against that initial value. If we find one that's bigger, we then reassign the highest variable to the element that was bigger. Once we do this for each element in the list, the number inside of highest will now be, just that, the highest number, and so, we'll return it to the main program.

    Similarly, we can do the same for finding the smallest.

    def get_smallest_number(input_list):
        smallest = input_list[0]
        for i in input_list:
            if i < smallest:
                smallest = i
        return smallest
    

    Finally, we get to our main loop. Here we declare an empty list, number_list to store all the numbers in. And we use the sum of that as our loop condition.

    if __name__ == '__main__':
        number_list = []
        while sum(number_list) < 179:
            number_list.append(get_input_number())
    

    In the body of the loop, we call our get_input_number() and append its result to the list we made. Once the sum of the numbers in the list exceed 179, the while loop will exit and we can finally show the user the results.

        print 
        print '-------------------------'
        print 'total of numbers entered: %d' % sum(number_list)
        print 'greatest number entered: %d' % get_greatest_number(number_list)
        print 'smallest number entered: %d' % get_smallest_number(number_list)
    

    Here we can the get_greatest_number and get_smallest_number we made, and we give them the list of numbers as an argument. They'll loop though the lists, and then return the appropriate values to the print statements.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-16 17:18

    here some well-known tricks:

        def min_and_max(your_num_list)
            min=your_num_list[0]
            max=your_num_list[0]
            for num in your_num_list:
                if num < min:
                    min=num
                if max > num
                    max=num
            return min,max
    
    0 讨论(0)
提交回复
热议问题