How to break a program if a string is entered in python [closed]

So I wrote a program to find the second largest number. The thing is, I want my program to show the second largest number when an enter key is pressed. But I also want my program to show an error when a string is entered. Here is my code:

#py program to find second largest number by user

nums = []
while True:
user = input("Enter a number. To stop press enter")
nums.append(user)
if user=="":
    break
if user==str:
    print("you have to enter a number!")
    break
nums.remove(max(nums))
print("Second largest number is: ", max(nums))

I know that 7th line is not good. Thanks for help 🙂

Answer

The comparison user==str doesn’t do what you want for two reasons:

  1. To test if something is a str, you’d want to be comparing its type to str, not the object itself — e.g. type(user) == str, or maybe isinstance(user, str).
  2. Testing whether user is a str is pointless anyway though, because it is always a str, even if it contains only numeric characters. What you really want to know is whether or not it is a str whose value allows it to be converted to an int (or maybe a float).

The simplest way to do this is to have a line of code that does the int conversion inside a try block, and catch the ValueError to print the error message if the conversion fails.

nums = []
while True:
    # indented code is inside the loop
    user = input("Enter a number. To stop press enter")
    if user == "":
        # stop the loop completely on empty input
        break
    try:
        nums.append(int(user))
    except ValueError:
        # print an error if it didn't convert to an int
        print("you have to enter a number!")
# unindented code is after the loop
nums.remove(max(nums))
print("Second largest number is: ", max(nums))