using python !! Write a function printTwoLargest() that inputs an arbitrary numb
ID: 3683460 • Letter: U
Question
using python !!
Write a function printTwoLargest() that inputs an arbitrary number of positive numbers from the user. The input of numbers stops when the first negative or zero value is entered by the user. The function then prints the two largest values entered by the user. If no positive numbers are entered a message to that effect is printed instead of printing any numbers. If only one number is inputted, only the largest is printed out (see 2nd example below). Sample output:
>>> printTwoLargest()
Please enter a number: 12
Please enter a number: 99.9
Please enter a number: 4.5
Please enter a number: 77
Please enter a number: 0
The largest is 99.9
The second largest is 77
>>> printTwoLargest()
Please enter a number: 23.2
Please enter a number: -99
The largest is 23.2
>>> printTwoLargest()
Please enter a number: -9
No positive numbers were entered
Explanation / Answer
def printTwoLargest():
print "Enter numbers, stops when negative value is entered:"
nums = []
while True:
try: n = int(raw_input("Please 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 "The Largest is {}".format(max(nums))
largest, larger = nums[0], nums[0]
for num in nums:
if num > largest:
largest, larger = num, largest
elif num > larger:
larger = num
print "The second largest is", larger
printTwoLargest()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.