Home > Mobile >  Separating two print() outputs under a while loop
Separating two print() outputs under a while loop

Time:07-01

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?

CodePudding user response:

if i understand your question properly, this should work.

n = int(input("Enter number of real numbers: "))
nums = []

for i in range(n):
    nums.append(float(input(f"Number#{i 1}: ")))
    
nums.sort()

l = ['first', 'second']

for i in range(0,n):
    if i>1:
        break
    
    print(f'{l[i]} highest number is: {nums[-(i 1)]} ')
else:
    print('There is no second highest number')
    
"""
Enter number of real numbers: 5

Number#1: 100

Number#2: 20

Number#3: 50

Number#4: 60

Number#5: 11
first highest number is: 100.0 
second highest number is: 60.0 
"""

"""
Enter number of real numbers: 1

Number#1: 10
first highest number is: 10.0 
There is no second highest number
"""

CodePudding user response:

Put the while loop under else statement. It will not execute as long as n==1

  • Related