Error Trapping Strings and Integers - python

I am trying to create an error trap using a try-except catch to prevent the user from entering a string, however when I run the code, it does not catch the error.
info=False
count=input("How many orders would you like to place? ")
while info == False:
try:
count*1
break
except TypeError:
print("Please enter a number next time.")
quit()
#code continues

A better way to do this would be to use a try except block
while True:
try:
count=int(input("How many orders would you like to place? "))
break
except:
print("This is not a valid input. Try again\n")
print(count)

str times ìnt works perfectly in python: 'a'*3 = 'aaa'. no exception will be raised in your try block.
if you want to distiguish int from str:
try:
int(count)
except ValueError:
do_something_else()
note: it is ValueError and not TypeError.

The value that input returns is string.
you can try something like this:
try:
val = int(userInput)
except ValueError:
print("That's not an int!")

You can use TypeError in the following way.
while True:
try:
count=input("How many orders would you like to place? ")
count += 1
except TypeError:
print("Please enter a number next time.")
break
Note that, a string can be multiplied by integer in python, so I have used addition operation since we cannot add integer to string in python.

Related

How to use the try-except command in a while loop asking for user input

I'm a Python beginner and tried to use try and except for the first time. I'm asking the user for an integer value but instead of ending the program if the user enters for example a string, I would like to ask the user again and again until an integer is given.
At the moment the user is only asked once to give another answer if he gives a string but if he gives a wrong input again, the program stops.
Below an example of what I mean.
I had a look through similar questions on Stackoverflow but I couldn't fix it with any of the suggestions.
travel_score = 0
while True:
try:
travel_score = int(input("How many times per year do you travel? Please give an integer number"))
except ValueError:
travel_score = int(input("This was not a valid input please try again"))
print ("User travels per year:", travel_score)
The problem is that there is no exception handling for your second input.
travel_score = 0
while True:
try:
travel_score = int(input("How many times per year do you travel? Please give an integer number"))
except ValueError:
# if an exception raised here it propagates
travel_score = int(input("This was not a valid input please try again"))
print ("User travels per year:", travel_score)
The best way to handle this is to put an informative message back to the user if their input is invalid and allow the loop to return to the beginning and re-prompt that way:
# there is no need to instantiate the travel_score variable
while True:
try:
travel_score = int(input("How many times per year do you travel? Please give an integer number"))
except ValueError:
print("This was not a valid input please try again")
else:
break # <-- if the user inputs a valid score, this will break the input loop
print ("User travels per year:", travel_score)
#Luca Bezerras answer is good, but you can get it a bit more compact:
travel_score = input("How many times per year do you travel? Please give an integer number: ")
while type(travel_score) is not int:
try:
travel_score = int(travel_score)
except ValueError:
travel_score = input("This was not a valid input please try again: ")
print ("User travels per year:", travel_score)
The problem is that once you thrown the ValueError exception, it is caught in the except block, but then if it is thrown again there are no more excepts to catch these new errors. The solution is to convert the answer only in the try block, not immediately after the user input is given.
Try this:
travel_score = 0
is_int = False
answer = input("How many times per year do you travel? Please give an integer number: ")
while not is_int:
try:
answer = int(answer)
is_int = True
travel_score = answer
except ValueError:
answer = input("This was not a valid input please try again: ")
print ("User travels per year:", travel_score)

Python - Syntax Error With 'Exception'

I'm trying to check to see wether or not an input is an integer but I keep on getting a syntax error. The code is as follows, thanks!
try:
offset=int(input("How Much Would You Like To Offset By?\n"))
except ValueError:
while offset!=int:
print("Please Enter An Integer!")
offset=int(input("How Much Would You Like To Offset By?\m"))
except ValueError
As stated in the comments, you need to indent your code correctly. You could for example use an IDE like Spyder which is free and relatively lightweight. In addition you also have an except at the end of your code that shouldn't be there. However, looking at your code in further detail, there are additional issues. Your while loop is currently not doing what you expect it to do and if you are using Python 2.x you will need to replace input with raw_input
try:
offset=int(raw_input("How Much Would You Like To Offset By?\n"))
except ValueError:
while offset!=int:
print("Please Enter An Integer!")
offset=int(input("How Much Would You Like To Offset By?\m"))
I suspect you want to do something like this, where you keep asking the user for an input until a valid integer has been entered:
offset = None
while not(offset):
try:
offset=int(input("How Much Would You Like To Offset By?\n"))
except ValueError:
print("Your input was not a valid number, please try again")
offset = None
You're almost there, just not quite. As noted in the comments, one issue you have in your original code is the indentation for the first except.
Once you fix this, you've then got a second issue:
>>> def get_offset():
... try:
... offset=int(input("How Much Would You Like To Offset By?\n"))
...
... except ValueError:
... while offset!=int:
... print("Please Enter An Integer!")
... offset=int(input("How Much Would You Like To Offset By?\m"))
... except ValueError
File "<stdin>", line 9
except ValueError
^
SyntaxError: invalid syntax
>>>
You're getting this issue from the second except ValueError, since there's no
try associated with it. If you fixed this, you'd then get an error because the following line references the value of offset before it's actually assigned:
while offset!=int:
If the initial attempt to convert the value entered in the input() statement fails, then no value is actually assigned to offset, which is what causes this error.
I would approach it as follows:
>>> def get_offset():
... while True:
... try:
... offset = int(input("How Much Would You Like To Offset By?\n"))
... break # Exit the loop after a valid integer has been entered.
...
... except ValueError:
... print("Please enter an integer!")
...
... return offset
...
>>> x = get_offset()
How Much Would You Like To Offset By?
5
>>> print(x)
5
>>> x = get_offset()
How Much Would You Like To Offset By?
spam
Please enter an integer!
How Much Would You Like To Offset By?
eggs
Please enter an integer!
How Much Would You Like To Offset By?
27
>>> print(x)
27
>>>
This allows you to keep querying for the offset value until a valid integer is entered.

How to convert input to float with exception handling

I'm trying to make sure that the user gave a valid floating point number as input.
run='yes'
valid='no'
x=1
while run == 'yes':
while valid == 'no':
x=float(input('Enter the richter scale you wish to convert:'))
check=isinstance(x,float)
if check == False:
print('Invalid value, re-try:')
valid=yes
float(x)`enter code here`
square=1.5*x+4.8
e=10**square
print(e)
tnt=e/4.184*10**9
print(tnt)
You need to use a try, except block. Something like this:
x = input('Enter the richter scale you wish to convert:')
try:
x = float(x)
except ValueError:
print("Sorry, that's not a valid float")
I am deliberately leaving the call to input outside of the try, except so that the value can be used for debugging purposes, and so that in case input some how throws an exception, it's not being caught by this block. Only the conversion to float should be wrapped in this block.

Having trouble requesting input in python

i have troubling handling input in python. I have a program that request from the user the number of recommendations to be calculated.He can enter any positive integer and blank(""). I tried using the "try: , except: " commands,but then i leave out the possibility of blank input. By the way blank means that the recommendations are going to be 10.
I tried using the ascii module,but my program ends up being completely confusing. I would be glad if anyone could get me on the idea or give me an example of how to handle this matter.
My program for this input is :
while input_ok==False:
try:
print "Enter the number of the recommendations you want to be displayed.\
You can leave blank for the default number of recommendations(10)",
number_of_recs=input()
input_ok=True
except:
input_ok=False
P.S. Just to make sure thenumber_of_recs , can either be positive integer or blank. Letters and negative numbers should be ignored cause they create errors or infinite loops in the rest of the program.
while True:
print ("Enter the number of the recommendations you want to " +
"be displayed. You can leave blank for the " +
"default number of recommendations(10)"),
number_of_recs = 10 # we set the default value
user_input = raw_input()
if user_input.strip() == '':
break # we leave default value as it is
try:
# we try to convert string from user to int
# if it fails, ValueError occurs:
number_of_recs = int(user_input)
# *we* raise error 'manually' if we don't like value:
if number_of_recs < 0:
raise ValueError
else:
break # if value was OK, we break out of the loop
except ValueError:
print "You must enter a positive integer"
continue
print number_of_recs

Try statement - multiple conditions - Python 2

I have little problem with try statement along with multiple conditions. When there is error at 2nd condition, it asks for 1st condition. What I want from it to do is to repeat the same condition, not the whole cycle. I hope you understand me, since my English isn't very good and also I'm newbie to Python so I also don't know how to describe it in my native language.
I hope the following example will help you to better understand my thought.
while True:
try:
zacatek = float(raw_input("Zacatek: "))
konec = float(raw_input("Konec: "))
except Exception:
pass
else:
break
it does following:
Zacatek: 1
Konec: a
Zacatek:
but I want it to do this:
Zacatek: 1
Konec: a
Konec:
Thanks in advance for any help.
Write a function to query for a single float, and call it twice:
def input_float(msg):
while True:
try:
return float(raw_input(msg))
except ValueError:
pass
zacatek = input_float("Zacatek: ")
konec = input_float("Konec: ")
What's happening is that your except clause is catching a ValueError exception on your answer to Konec and returning to the top of the loop.
Your float function is trying to cast a non-numeric response "a" to a float and it throwing the exception.
Alternatively, you could write a different loop for each input:
zacatek = None
while not zacatek:
try:
zacatek = float(raw_input("Zacatek: "))
except Exception:
continue
konec = None
while not konec:
try:
konec = float(raw_input("Konec: "))
except Exception:
continue

Categories