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


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))

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