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 = []
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]