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
Related
I have simple code:
def simpleMethod():
try:
list_to_app = []
number_of_a = input('\nHow many a you want to create? ')
number_of_a = int(number_of_a)
for i in range(number_of_a):
user_a = input('\nPlease type here some track: ')
list_to_app.append(user_a.lower())
except ValueError:
stderr.write('Type error - please provide an integer character')
simpleMethod()
I do not want to use something like while True:...
How to make some loop (I think while will be fine in this case) for this kind of flow:
user types non-integer
program shows Type error - please provide an integer character
program goes back to 1. step
This is simple method but I'm stuck.
Add a while True loop to repeat the try block until it can successfully break. You probably also want to return the list you're building so that the caller can access it:
def simpleMethod():
list_to_app = []
while True:
try:
number_of_a = input('\nHow many a you want to create? ')
number_of_a = int(number_of_a)
break
except ValueError:
stderr.write('Type error - please provide an integer character')
for i in range(number_of_a):
user_a = input('\nPlease type here some track: ')
list_to_app.append(user_a.lower())
return list_to_app # no point building a list you don't return!
tracks = simpleMethod()
A simpler way to build a list is a comprehension -- you can actually put almost the entire function in a single comprehension statement within that while, since the exception will raise to the outer loop. You might also want to make the function name more descriptive:
from typing import List
def get_user_tracks() -> List[str]:
"""Prompt the user for a list of tracks."""
while True:
try:
return [
input('\nPlease type here some track: ')
for _ in range(int(input('\nHow many a you want to create? ')))
]
except ValueError:
stderr.write('Type error - please provide an integer character')
tracks = get_user_tracks()
we are beginners and want to code the game Mastermind in Python. (Please see our code below.)
Problem:
We want to end the execution of the code if the 'StopIteration' error occurs in the 'while' loop. But somehow 'quit()' doesn't work in this place. Can anyone give us a clue how to solve this problem?
def inconsistent(new_guess, guesses):
for guess in guesses:
res = check(guess[0], new_guess)
(rightly_positioned, right_colour) = guess[1]
if res != [rightly_positioned, right_colour]:
return True # inconsistent
return False # i.e. consistent
while inconsistent (new_guess, guesses):
try:
new_guess=next(generator)
except StopIteration:
print("Error: Your answers were inconsistent!")
break
Break should work. If you want to skip this guess you could use
continue
I did this example but it does not run with the try and except handling errors in Python.
def my_fun(numCats):
print('How many cats do you have?')
numCats = input()
try:
if int(numCats) >=4:
print('That is a lot of cats')
else:
print('That is not that many cats')
except ValueError:
print("Value error")
I tried:
except Exception:
except (ZeroDivisionError,ValueError) as e:
except (ZeroDivisionError,ValueError) as error:
I did other example and it was able to catch ZeroDivisionError
I am using Jupyter notebook Python 3.
Any help in this matter is highly appreciated.
I am calling
my_fun(int('six'))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-39-657852cb9525> in <module>()
----> 1 my_fun(int('six'))
ValueError: invalid literal for int() with base 10: 'six'
A few problems:
Please fix the indentation. The indentation levels are mismatched.
There's no need to take in the parameter numCats as it's changed to whatever the user provides anyway.
You're not calling the function my_fun(), meaning that there will never be any output, as functions only run when called.
This should work:
def my_fun():
print('How many cats do you have?\n')
numCats = input()
try:
if int(numCats) > 3:
print('That is a lot of cats.')
else:
print('That is not that many cats.')
except ValueError:
print("Value error")
my_fun() ## As the function is called, it will produce output now
Here is a reworked version of your code:
def my_fun():
numCats = input('How many cats do you have?\n')
try:
if int(numCats) >= 4:
return 'That is a lot of cats'
else:
return 'That is not that many cats'
except ValueError:
return 'Error: you entered a non-numeric value: {0}'.format(numCats)
my_fun()
Explanation
You need to call your function for it to run, as above.
Indentation is important. This has been made consistent with guidelines.
input() takes as a parameter a string which is displayed before the input.
Since the user provides input via input(), your function does not require an argument.
It is good practice to return values and, if necessary, print them afterwards. Rather than having your function print strings and return None.
Your error can be more descriptive, and include the inappropriate input itself.
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.
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.