编写读取数字的程序,而不输入负数。结果,在输入的值中打印最大数量

时间:2013-10-07 17:11:30

标签: python python-2.7

我试着写一下:

print "Enter numbers, stops when negative value is entered:"
numbers = [input('value: ') for i in range(10)]
while numbers<0:
但突然之间,我失去理智,不知道接下来要做什么

示例是:

  

输入数字,输入负值时停止:

     

值:5

     

值:9

     

值:2

     

值:4

     

值:8

     

值:-1

     

最大值为9

3 个答案:

答案 0 :(得分:0)

这就是你要找的东西:

print "Enter numbers, stops when negative value is entered:"
nums = []
while True: # infinite loop
    try: n = int(raw_input("Enter a number: ")) # raw_input returns a string, so convert to an integer
    except ValueError: 
        n = -1
        print "Not a number!"
    if n < 0: break # when n is negative, break out of the loop
    else: nums.append(n)
print "Maximum number: {}".format(max(nums))

答案 1 :(得分:0)

听起来你想要这些内容:

def get_number():
    num = 0
    while True: # Loop until they enter a number
        try:
            # Get a string input from the user and try converting to an int
            num = int(raw_input('value: '))
            break
         except ValueError:
            # They gave us something that's not an integer - catch it and keep trying
            "That's not a number!"

     # Done looping, return our number
     return num

print "Enter numbers, stops when negative value is entered:"
nums = []
num = get_number() # Initial number - they have to enter at least one (for sanity)
while num >= 0: # While we get positive numbers
    # We start with the append so the negative number doesn't end up in the list
    nums.append(num)
    num = get_number()

print "Max is: {}".format(max(nums))

答案 2 :(得分:0)

我想你想要这样的东西:

# Show the startup message
print "Enter numbers, stops when negative value is entered:"

# This is the list of numbers
numbers = []

# Loop continuously
while True:

    try:
        # Get the input and make it an integer
        num = int(raw_input("value: "))

    # If a ValueError is raised, it means input wasn't a number
    except ValueError:

        # Jump back to the top of the loop
        continue

    # Check if the input is positive
    if num < 0:

        # If we have got here, it means input was bad (negative)
        # So, we break the loop
        break

    # If we have got here, it means input was good
    # So, we append it to the list
    numbers.append(num)

# Show the maximum number in the list
print "Maximum is", max(numbers)

演示:

  

输入数字,输入负值时停止:

     

值:5

     

值:9

     

值:2

     

值:4

     

值:8

     

值:-1

     

最大值为9