Can't create an while infinite loop - python

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!")

Related

How to understand exception condition usage in Python?

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.

Try-Except block - Did I do this correctly?

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: ')
...

If statement based on invalid class entered in Python

I'm quite new to python and I'm trying to create a program that uses an if statement that is based on if an int input ( int(input()) ) gets the right input class. For example: if I have an input that goes Var1 = int(input("Enter a number:...")), and the user enters hello there, this would, instead of giving an error message, go into one of the options in an if statement.
Since the rest of the code hasn't been created yet I can't post it, but I've tried all the ways I've come up with to solve this problem without success... Can anyone help me please?
You can surround your input with a try..except block and capture a ValueError that will occur when int() tries to convert a non-integer into an integer:
try:
var1 = int(input("Enter an integer: "))
except ValueError:
print("That's not an integer!")
You can even force your users to enter an integer by placing it in a loop:
var1 = None
while var1 is None:
try:
var1 = int(input("Enter an integer: "))
except ValueError:
print("That's not an integer!")
Or you can do checks at a later time:
var1 = input("Enter an integer: ")
try:
var1 = int(var1)
print("Thank you for entering an integer.")
except ValueError:
print("That's not an integer!")
You can use try/except:
while(True):
try:
var1 = int(input("enter a number: "))
break
except ValueError:
print('it should be a number')
caution: don't use try/except without Execption type like:
try:
printo('hi')
except:
pass
it will except all excetions even syntax error

How do I avoid error while using int()?

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.

Printing numbers as long as an empty input is not entered

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

Categories