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:
- To test if something is a
str
, you'd want to be comparing its type tostr
, not the object itself -- e.g.type(user) == str
, or maybeisinstance(user, str)
. - Testing whether
user
is astr
is pointless anyway though, because it is always astr
, even if it contains only numeric characters. What you really want to know is whether or not it is astr
whose value allows it to be converted to anint
(or maybe afloat
).
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"