I came across a code that keeps asking the user for input until the user finally input an integer.
while True:
try:
n = input('Please enter an integer.')
n = int(n)
break
except ValueError:
print('Input is not an integer. Try again.')
print('Correct input of an integer.')
I tried out the code by entering a string as input and it asks me to try again. I assume it gives me a ValueError when it is executing
n = int(n)
as it can not convert a string to integer. Which the code then jumps to execute the except condition. However, I don't understand why am I still in the while loop after executing the except condition? It doesn't return True or something to continue running the while loop?
Also I entered a float as my input and it again ask me to try again. I do not understand as wouldn't int(n) be able to convert my float input to an integer without any ValueError?
You need to add a break statement after print('Input is not an integer. Try again.') or else it will keep looping back. As for handling floats, you could use int(float(n)) as suggested by tdelaney.
while True:
try:
n = input('Please enter an integer.')
n = int(float(n))
print('Correct input of an integer.')
break
except ValueError:
print('Input is not an integer. Try again.')
break
You can use the trace module to see statement by statement execution of the code:
$ python -m trace -t test.py
--- modulename: test, funcname: <module>
test.py(1): while True:
test.py(2): try:
test.py(3): n = input('Please enter an integer.')
Please enter an integer.notaninteger
test.py(4): n = int(n)
test.py(6): except ValueError:
test.py(7): print('Input is not an integer. Try again.')
Input is not an integer. Try again.
test.py(2): try:
test.py(3): n = input('Please enter an integer.')
Please enter an integer.1.1
test.py(4): n = int(n)
test.py(6): except ValueError:
test.py(7): print('Input is not an integer. Try again.')
Input is not an integer. Try again.
test.py(2): try:
test.py(3): n = input('Please enter an integer.')
Please enter an integer.3
test.py(4): n = int(n)
test.py(5): break
test.py(9): print('Correct input of an integer.')
Correct input of an integer.
In the first two test cases, the exception is run and you end up back at the top of the loop. In the final case, the break is hit which breaks you out of the nearest enclosing loop... the while.
Related
I'm trying to build a loop in PyCharm to force the user to submit only integers to the program.
But so far, I've only got the input in loop.
What should I do?
You have to cast the input(). In case the user provides a non-integer number, int() will throw a ValueError you you can subsequently handle as below
while True:
try:
num = int(input("Insert an integer number: "))
except ValueError:
print("Sorry, you must enter an integer.")
continue
else:
print(f"The number is: {num}")
break
This is because input always returns a string. What you can do is to try and convert this string into an int, catch the exception raised when this conversion fails, and ask user to try again. For example, like this:
x = None
while x is None:
try:
x = int(input("Enter Number:"))
except ValueError:
print("Oops, this doesn't seem right, try again!")
We are learning exception handling. Did I do this correctly? Is ValueError the correct exception to use to catch strings being typed instead of numbers? I tried to use TypeError, but it doesn't catch the exception.
Also, is there a more efficient way to catch each exception in my four inputs? What is best practice here?
#Ask user for ranges. String inputs are not accepted and caught as exceptions. While loop repeats asking user for input until a float number is input.
while True:
try:
rangeLower = float(input("Enter your Lower range: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
while True:
try:
rangeHigher = float(input("Enter your Higher range: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
#Ask user for numbers. String inputs are not accepted and caught as exceptions. While loop repeats asking user for input until a float number is input.
while True:
try:
num1 = float(input("Enter your First number: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
while True:
try:
num2 = float(input("Enter your Second number: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
Here you are experiencing what is called, WET code Write Everything Twice, we try to write DRY code, i.e. Don't Repeat Yourself.
In your case what you should do is create a function called float_input as using your try except block and calling that for each variable assignment.
def float_input(msg):
while True:
try:
return float(input(msg))
except ValueError:
pass
range_lower = float_input('Enter your lower range: ')
...
I am trying to create a program where the user has to input 3 numbers to be displayed by the range function. However, I am trying to assign a numerical value to when an empty input is given to one of the variables. Here is part of my code. For this section of the code, I want to assign a value of zero when the user enters empty input. However, when I try running this section of the program, I get this error: line 5, in
number = int(input_value)
ValueError: invalid literal for int() with base 10: ''
Any suggestions are greatly appreciated!
while True:
input_value = input("Type a number: ")
number = int(input_value)
if input_value.isalpha():
print("Not a number")
break
else:
if input_value is None:
number = int(0)
break
else:
if int(number):
break
print(number)
When a user input is empty, input_value will be "", which python cannot convert to an integer. number = int("") will throw an error.
What you can do is check if the input is equal "" and if it is, set number to 0, else convert it using int().
Better yet, I would wrap number = int(input_value) in a try catch statement:
while True:
input_value = input("Type a number: ")
try:
number = int(input_value)
except:
print("invalid input")
break
So to break the loop, you'd enter something thats not a number. In this case, you'd only be storing the last input value into number, so it's up to you how you want to keep track of all the inputs (probably using a list).
just a thought:
while True:
input_value = input("Type a number: ")
if input_value:
try:
number = int(input_value)
break
except:
continue
print(number)
I have a question concerning int(). Part of my Python codes looks like this
string = input('Enter your number:')
n = int(string)
print n
So if the input string of int() is not a number, Python will report ValueError and stop running the remaining codes.
I wonder if there is a way to make the program re-ask for a valid string? So that the program won't just stop there.
Thanks!
You can use try except
while True:
try:
string = input('Enter your number:')
n = int(string)
print n
break
except ValueError:
pass
Put the whole thing in an infinite loop. You should catch and ignore ValueErrors but break out of the loop when you get a valid integer.
What you're looking for isTry / Except
How it works:
try:
# Code to "try".
except:
# If there's an error, trap the exception and continue.
continue
For your scenario:
def GetInput():
try:
string = input('Enter your number:')
n = int(string)
print n
except:
# Try to get input again.
GetInput()
n = None
while not isinstance(n, int):
try:
n = int(input('Enter your number:'))
except:
print('NAN')
While the others have mentioned that you can use the following method,
try :
except :
This is another way to do the same thing.
while True :
string = input('Enter your number:')
if string.isdigit() :
n = int(string)
print n
break
else :
print("You have not entered a valid number. Re-enter the number")
You can learn more about
Built-in String Functions from here.
If I'm asking for a user input of numbers which continues as long as an empty string is not entered, if an empty string is entered then the program ends.
My current code is:
n=0
while n != "":
n = int(input("Enter a number: "))
But obviously this isn't exactly what I want. I could remove the int input and leave it as a regular input, but this will allow all types of inputs and i just want numbers.
Do i ago about this a different way?
calling int() on an empty string will cause a ValueError so you can encapsulate everything in a try block:
>>> while True:
try:
n = int(input('NUMBER: '))
except ValueError:
print('Not an integer.')
break
NUMBER: 5
NUMBER: 12
NUMBER: 64
NUMBER:
not a number.
this also has the added benefit of catching anything ELSE that isn't an int.
I would suggest using a try/except here instead.
Also, with using a try/except, you can instead change your loop to using a while True. Then you can use break once an invalid input is found.
Also, your solution is not outputting anything either, so you might want to set up a print statement after you get the input.
Here is an example of how you can put all that together and test that an integer is entered only:
while True:
try:
n = int(input("Enter a number: "))
print(n)
except ValueError:
print("You did not enter a number")
break
If you want to go a step further, and handle numbers with decimals as well, you can try to cast to float instead:
while True:
try:
n = float(input("Enter a number: "))
print(n)
except ValueError:
print("You did not enter a number")
break