Skip to content Skip to sidebar Skip to footer

How To Break A Program If A String Is Entered In Python

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 t

Solution 1:

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 = []
whileTrue:
    # indented code is inside the loop
    user = input("Enter a number. To stop press enter")
    if user == "":
        # stop the loop completely on empty inputbreaktry:
        nums.append(int(user))
    except ValueError:
        # print an error if it didn't convert to an intprint("you have to enter a number!")
# unindented code is after the loop
nums.remove(max(nums))
print("Second largest number is: ", max(nums))

Post a Comment for "How To Break A Program If A String Is Entered In Python"