Question: Enter a value for n, and the code takes n floating numbers and prints out the first highest and second-highest numbers.
Sample Output 1:
Enter number of real numbers: 5 Number#1: 45.23 Number#2: 23.5 Number#3: 12 Number#4: 12.321 Number#5: 105.5 The first highest number is 105.5 The second-highest number is 45.23
Sample Output 2:
Enter number of real numbers: 1 Number#1: 100.275 The first highest number is 105.5 There is no second highest number.
My code:
n = int(input("Enter number of real numbers: ")) ctr = 0 firsth = 0 secondh = 0 if n == 1: temp = float(input(f"Number#{ctr+1}: ")) firsth = temp print(f"The first highest number is {firsth} nThere is no second highest number. n") while ctr < n and n != 1: temp = float(input(f"Number#{ctr+1}: ")) ctr += 1 if temp > firsth: secondh = firsth firsth = temp elif temp > secondh: secondh = temp print(f"The first highest number is {firsth} nThe second highest number is {secondh} n")
I tried several times that my code will eventually print both outputs of when n == 1
and of the while
-loop. Any idea on how to print only one output when n == 1
?
Advertisement
Answer
Put the while loop under else statement. It will not execute as long as n==1