Force a user to put in a intger - python

How could I force an user to put in an integer? I am wondering if I should a 'while' statement. This is the idea I got from here.
x = raw_input("put in a number")
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False

Something like this should work:
while True:
try:
x = int(raw_input("put in a number"))
break
except ValueError:
continue # or maybe print a message here...

Related

Try-Except ErrorCatching

I'm trying to force the user to input a number using try-except in python however it seems to have no effect.
while count>0:
count=count - 1
while (length != 8):
GTIN=input("Please enter a product code ")
length= len(str(GTIN))
if length!= 8:
print("That is not an eight digit number")
count=count + 1
while valid == False:
try:
GTIN/5
valid = True
except ValueError:
print("That is an invalid number")
count=count + 1
Actually, if the user inputs for example a string, "hello"/5 yields a TypeError, not a ValueError, so catch that instead
You could try to make the input value an int int(value), which raises ValueError if it cannot be converted.
Here's a function that should do what you want with some comments:
def get_product_code():
value = ""
while True: # this will be escaped by the return
# get input from user and strip any extra whitespace: " input "
value = raw_input("Please enter a product code ").strip()
#if not value: # escape from input if nothing is entered
# return None
try:
int(value) # test if value is a number
except ValueError: # raised if cannot convert to an int
print("Input value is not a number")
value = ""
else: # an Exception was not raised
if len(value) == 8: # looks like a valid product code!
return value
else:
print("Input is not an eight digit number")
Once defined, call the function to get input from the user
product_code = get_product_code()
You should also be sure to except and handle KeyboardInterrupt anytime you're expecting user input, because they may put in ^C or something else to crash your program.
product code = None # prevent reference before assignment bugs
try:
product_code = get_product_code() # get code from the user
except KeyboardInterrupt: # catch user attempts to quit
print("^C\nInterrupted by user")
if product_code:
pass # do whatever you want with your product code
else:
print("no product code available!")
# perhaps exit here

ValueError exception not working in python

I'm trying to make a simple program that will calculate the area of a circle when I input the radius. When I input a number it works, but when I input something else I'd like it to say "That's not a number" and let me try again instead of giving me an error.
I can't figure out why this is not working.
from math import pi
def get_area(r):
area = pi * (r**2)
print "A= %d" % area
def is_number(number):
try:
float(number)
return True
except ValueError:
return False
loop = True
while loop == True:
radius = input("Enter circle radius:")
if is_number(radius) == True:
get_area(radius)
loop = False
else:
print "That's not a number!"
When you don't input a number, the error is thrown by input itself which is not in the scope of your try/except. You can simply discard the is_number function altogether which is quite redundant and put the print statement in the except block:
try:
radius = input("Enter circle radius:")
except (ValueError, NameError):
print "That's not a number!"
get_area(radius)
radius is still a string,
replace
get_area(radius)
with
get_area(float(radius))
You also have to replace input with raw_input since you're using Python 2
in= 0
while True:
try:
in= int(input("Enter something: "))
except ValueError:
print("Not an integer!")
continue
else:
print("Yes an integer!")
break

Try- except ValueError loop

def enterNumber():
number = input("Please enter a number to convert to binary. ")
while True:
try:
int(number)
convertDenary()
except ValueError:
enterNumber()
def convertDenary():
binaryNumber = ['','','','','','','','']
print(enterNumber())
if enterNumber() > 128:
enterNumber() - 128
binaryNumber[0] == 1
enterNumber()
The Try- Except ValueError does loop as I intend it to however, it won't break. I've tried adding in break under the int(number), removing the while True: and added in the convertDenary() to see if it will force the subroutine to stop and start the other but it still doesn't work.
I get an infinite loop of "Please enter a number to convert to binary."
Any ideas?
def convertToBinary(number):
if number > 1:
convertToBinary(number//2)
elif number<1:
enterNumber()
print(number % 2,end = '')
def enterNumber():
number = (input("Please enter a number to convert to binary : "))
try:
convertToBinary(int(number))
except Exception as e:
print(e)
enterNumber()

Python 3 - Code will not recognize a user input larger than 1 as numeric

I created the following python code for an exercise in Python for informatics. The code will run, but will not recognize an input form the user that is larger than 1 as numeric. Any assistance would be appreciated.
def isfloat(string):
try:
float(string)
if float(string) == True:
return True
except ValueError:
return False
user_input = input('Please enter a real number. Type \"done\" to exit and tally your entries \n> ')
data = 0
count = 0
while isfloat(user_input) == True:
data = data + float(user_input)
count = count + 1
user_input = input("Please enter another value \n> ")
isfloat(user_input)
else:
if (isfloat(user_input) == False) and (user_input == "done"):
print("The sum of your entries is: " + str(data))
print("The number of entries was: " + str(count))
exit()
else:
print("The entry was not a numeric value \n")
print("The sum of your valid entries is: " + str(data))
print("The number of valid entries was: " + str(count))
exit()
This is ridiculous:
if float(string) == True:
That's checking if the float converted value is equal to True (which is numerically 1).
Just check for the exception and go:
def isfloat(string):
try:
float(string)
except ValueError:
return False
else:
return True
The problem lies in the fact that float(string) will never return True; it will always return a number of type float or it will raise a ValueError if the input cannot be converted to a float.
To fix this, you'll need to remove your if statement, and simply return True after calling float(string) in your isfloat function. If float(string) raises a ValueError, isfloat returns False as you would expect; otherwise, it will proceed and return True.
def isfloat(string):
try:
float(string)
return True
except ValueError:
return False
The problem is with your isfloat. You shouldn't compare the result of float with True. Instead do something like:
def isfloat(string):
try:
float(string)
return True
except ValueError:
return False
You don't need to actually do anything with the return value of float. If that call doesn't trigger an error -- you have a float, so just return True.
It might be tempting to use the line
if float(string): return True
That would almost work but would misclassify "0"

How can I make a Validation Try and Except Error for this?

I have this code as shown below and I would like to make a function which has a try and except error which makes it so when you input anything other than 1, 2 or 3 it will make you re input it. Below is the line which asks you for your age.
Age = input("What is your age? 1, 2 or 3: ")
Below this is what I have so far to try and achieve what I want.
def Age_inputter(prompt=' '):
while True:
try:
return int(input(prompt))
except ValueError:
print("Not a valid input (an integer is expected)")
any ideas?
add a check before return then raise if check fails:
def Age_inputter(prompt=' '):
while True:
try:
age = int(input(prompt))
if age not in [1,2,3]: raise ValueError
return age
except ValueError:
print("Not a valid input (an integer is expected)")
This may work:
def Age_inputter(prompt=' '):
while True:
try:
input_age = int(input(prompt))
if input_age not in [1, 2, 3]:
# ask the user to input his age again...
print 'Not a valid input (1, 2 or 3 is expected)'
continue
return input_age
except (ValueError, NameError):
print 'Not a valid input (an integer is expected)'

Categories

Resources