-4

Question is Find the 2nd largest digit ,What is wrong with my code, I am a beginner ,Output is still zero

a = input("Enter your number")
max = 0
maxx  = 0

list1 = []


for i in a :
    list1.append(i)
    if i > str(max) :
        max = i
        list1.remove(max)
        for j in list1 :
            if j > str(maxx) :
            maxx = j
print(maxx)
  • The line below the first `if` statement isn't indented correctly. Are you sure your code is indented right? – BrokenBenchmark Apr 25 '22 at 04:52
  • Just a tip, you shouldn't make a variable called `max` - it's a builtin function – Ryan Fu Apr 25 '22 at 05:33
  • 1
    Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Apr 25 '22 at 09:07

1 Answers1

0

The second for loop shouldn't have been nested and inside a conditional like that, since it would only run until the highest number was found.

The other main issue is that that even without the second for loop being nested, in a situation where a = '12345' every number is the highest the first loop finds and is therefore deleted from list1 meaning that list1 ends up completely empty.

This should work:

a = input("Enter your number: ")
max_num = 0
maxx  = 0


for i in a :
    if i > str(max_num) :
        max_num = i
        
for j in a :
    if j > str(maxx) and j < str(max_num):
        maxx = j
        
print(maxx)

or you can also do this:

nums = input('Enter numbers: ')
list1 = []

for i in nums:
    list1.append(int(i))
    
list1.sort()
print(list1[-2])