In the second line, I am trying to make it not crash if a string is entered but can't find a way to use an exception or something similar. In the while loop it works normally as the exception deals with this case.
number = 0 #this to be removed
number = (float(input('pick a number'))) #I want to make this not crash if a string is entered.
while number not in [100, 200, 3232]:
try:
print('wrong number ')
number = (float(input('pick a number;'))) #Here it does not crash if a string is entered which is fine
except ValueError:
print("retry")
while followed by a variable condition often ends up with bugs/repeating code => bad maintenability.
Use a while True condition to avoid repeating your code, then break out the loop when it's valid.
while True:
try:
number = float(input('pick a number;'))
if number in [100, 200, 3232]:
break
print("wrong number")
except ValueError:
print("illegal number, retry")
note: be careful with float equality in the general case (see also strange output in comparison of float with float literal, Is floating point math broken?)
Maybe create a function to take input:
def get_input():
while True:
a = input("Pick a number: ")
try:
return float(a)
except:
pass
Related
So, I have a homework where I'm assigned to write multiple python codes to accomplish certain tasks.
one of them is: Prompt user to input a text and an integer value. Repeat the string n
times and assign the result to a variable.
It's also mentioned that the code should be written in a way to avoid any errors (inputting integer when asked for text...)
Keep in mind this is the first time in my life I've attempted to write any code (I've looked up instructions for guidance)
import string
allowed_chars = string.ascii_letters + "'" + "-" + " "
allowed_chars.isalpha()
x = int
y = str
z = x and y
while True:
try:
x = int(input("Enter an integer: "))
except ValueError:
print("Please enter a valid integer: ")
continue
else:
break
while True:
try:
answer = str
y = answer(input("Enter a text: "))
except ValueError:
print("Please enter a valid text")
continue
else:
print(x*y)
break
This is what I got, validating the integer is working, but I can't validate the input for the text, it completes the operation for whatever input. I tried using the ".isalpha()" but it always results in "str is not callable"
I'm also a bit confused on the assigning the result to a variable part.
Any help would be greatly appreciated.
Looks like you are on the right track, but you have a lot of extra confusing items. I believe your real question is: how do I enforce alpha character string inputs?
In that case input() in python always returns a string.
So in your first case if you put in a valid integer say number 1, it actually returns "1". But then you try to convert it to an integer and if it fails the conversion you ask the user to try again.
In the second case, you have a lot of extra stuff. You only need to get the returned user input string y and check if is has only alpha characters in it. See below.
while True:
x = input("Enter an integer: ")
try:
x = int(x)
except ValueError:
print("Please enter a valid integer: ")
continue
break
while True:
y = input("Enter a text: ")
if not y.isalpha():
print("Please enter a valid text")
continue
else:
print(x*y)
break
I have this bit of code :
while True:
try:
start = int(input("Starting number: "))
fin = int(input("Ending number: "))
amount = int(input("Count by: "))
except ValueError as verr:
print('error : ', verr,'\n restarting ....')
else:
break
I would like to intercept the inputing of '' just hitting return as a signal to exit the loop inside the except block. Is there any way to get the value that raises the ValueError (I dont know how int() is able to return a ValueError and dont know about the latter either) other than parsing the ValueError __repr__ , for example :
invalid literal for int() with base 10: 'รจรจรจ' or the one I want to intercept
invalid literal for int() with base 10: '' ?
You could save the input value before the conversion and use that to check.
while True:
try:
_start = _fin = _amount = None
start = int(_start:=input("Starting number: "))
fin = int(_fin:=input("Ending number: "))
amount = int(_amount:=input("Count by: "))
except ValueError as verr:
if _start == "" or _fin == "" or _amount == "":
break
print('error : ', verr,'\n restarting ....')
else:
break
I think I would just get the inputs as strings then put an if statement to catch the case of '' or whatever else before converting to int and catching ValueErrors. This might offend if you are a stickler for concise code though.
Or as you say, parse the repr with something like .split(':')[-1]
Since the error is raised without passing the function argument and is formatted as string, there is no way to get the value directly from the error, what you can do is store it separately as a variable and then check the variable directly like so:
while True:
data = {"start": 0, "fin": 0, "amount": 0}
try:
for i in data:
x = input(f"Enter the value for {i}")
x = int(x)
data[i] = x
except ValueError:
if x == "":
break
Others have already posted possible solutions for your problem but to answer your question directly.
Question: Python ValueError is it possible to get the Incorrect Value without string parsing?
Answer: No it is not. ValueError only stores a message string and nothing else. You can get that message by str(verr) or verr.args[0]. The int(...) call already creates the full message and doesn't pass it's input string seperatly to the ValueError in any way. :/
I am a new learner for Python. I have a question about while loop.
I wrote a program below to look for square roots.
When I input anything but integers, the message "is not an integer" shows up and it repeats itself until I input correct data(integers).
My question is, why does it end loop when it return value on line 5, return(int(val))?
Thank you for your attention.
def readInt():
while True:
val = input('Enter an integer: ')
try:
return(int(val))
except ValueError:
print(val, "is not an integer")
g = readInt()
print("The square of the number you entered is", g**2)
To answer your original question, 'return' effectively exits the loop and provide the result that follows the 'return' statement, but you have to explicity print it like so:
def read_int(num1, num2):
while True:
return num1 + num2
print(read_int(12, 15))
If you simply put 'read_int(12, 14)' instead of 'print(read_int(12, 15))' in this scenario, you won't print anything but you will exit the loop.
If you allow me, here are some modifications to your original code:
def read_int(): # functions must be lowercase (Python convention)
while True:
val = input('Enter an integer: ')
try:
val = int(val) # converts the value entered to an integer
minimum_value = 0 # There is no need to evaluate a negative number as it will be positive anyway
maximum_value = 1000000 # Also, a number above 1 million would be pretty big
if minimum_value <= val <= maximum_value:
result = val ** 2
print(f'The square of the number you entered is {result}.')
# This print statement is equivalent to the following:
# print('The square of the number you entered is {}.'.format(result))
break # exits the loop: else you input an integer forever.
else:
print(f'Value must be between {minimum_value} and {maximum_value}.')
except ValueError: # If input is not an integer, print this message and go back to the beginning of the loop.
print(val, 'is not an integer.')
# There must be 2 blank lines before and after a function block
read_int()
With the final 'print' that you actually have at the end of your code, entering a string of text in the program generates an error. Now it doesn't ;). Hope this is useful in some way. Have a great day!
I'm just trying Python, and really like it! But I get stucked with try/except.
I have a code that checks raw_input for being integer, but i'd like to make it function, and it doesn't want to be it :)
here the code, I have this:
number_of_iterations = raw_input("What is your favorite number?")
try:
int(number_of_iterations)
is_number = True
except:
is_number = False
while not is_number:
print "Please put a number!"
number_of_iterations = raw_input("What is your favorite number?")
try:
int(number_of_iterations)
is_number = True
except:
is_number = False
I don't want to repeat myself here& So I think smth about to make function:
def check_input(input_number):
try:
int(input_number)
return True
except:
return False
But it make an error if input a string, saying that int can't be used for strings. Looks like it does not see 'try' keyword.
Can smone explain why it happens and how to prevent it in future?
Try this, it avoids repeating yourself without needing a def
while True:
try:
number_of_iterations = int(raw_input("What is your favorite integer?"))
break
except ValueError:
print "Please put an integer!"
EDIT: Per the suggestions of the commenters, I have added break to the try portion of the block to eliminate the else (the original remains as a reference below). Also, I changed "number" to "integer" because "3.14" would be invalid in the above code.
This was my original suggestion. The above is fewer lines (some may call this cleaner), but I prefer the below because to me the intent is clearer.
while True:
try:
number_of_iterations = int(raw_input("What is your favorite integer?"))
except ValueError:
print "Please put an integer!"
else:
break
If you want it as a function, decide two things:
What is it going to need to work, and
What it's going to need to spit back out.
Your use case is that you need some sort of int back, and if it bombs out for whatever reason, it's defined as not a number.
Let's create a tuple as our return value, so we can return a number of some kind and a boolean for "if it is a number".
def check_input(number):
try:
return (int(number), True)
except ValueError:
return (-999999, False) # Care more about boolean here
We can then use that return value in our while loop like so. Note that I explicitly set the loop condition to False, so we enter in at least once.
is_number = False
num = -999999 # Define out of scope of loop so it can be used
while not is_number:
print "Please put a number!"
num, is_number = check_input(raw_input("What is your favorite number?"))
The line num, is_number is a result of tuple packing. Since we're returning a tuple from our method, we can set two distinct variables to the results of that tuple.
Wondering if there is a better way to do this. Python is my first programming language.
while True:
amount_per_month = raw_input('\nWhat is the monthly cost?\n==> ')
# seperate dollars and cents.
amount_list = amount_per_month.split(".")
# checking if int(str) is digit
if len(amount_list) == 1 and amount_list[0].isdigit() == True:
break
# checking if float(str) is digit
elif len(amount_list) == 2 and amount_list[0].isdigit() and amount_list[1].isdigit() == True:
break
else:
raw_input('Only enter digits 0 - 9. Press Enter to try again.')
continue
Just try to make it a float and handle the exception thrown if it can't be converted.
try:
amount_per_month = float( raw_input('What is the monthly cost?') )
except (ValueError, TypeError) as e:
pass # wasn't valid
TypeError is redundant here, but if the conversion was operating on other Python objects (not just strings), then it would be required to catch things like float( [1, 2, 3] ).
You could try casting the input to a float, and catching the exception if the input is invalid:
amount_per_month = raw_input('\nWhat is the monthly cost?\n==> ')
try:
amt = float(amount_per_month)
except ValueError:
raw_input('Only enter digits 0 - 9. Press Enter to try again.')
use regex
r'\d+.\d+|\d+'
http://docs.python.org/library/re.html