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
Related
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
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()
try:
num=float(num)
except:
print "Invalid input"
continue
this part of my code seems to be bugging, but when i remove the try and except everything works smoothly, so this seems to be the problem.
i want to convert the input inside a while loop to an integer, if the input isn't an integer it'll display an error and just continue with the loop and ask again. however, it doesn't continue the loop and just keeps printing "Invalid input" forever. how come it isn't continuing the loop?
here is the entire code, in case something else might be wrong:
c=0
num2=0
num=raw_input("Enter a number.")
while num!=str("done"):
try:
num=float(num)
except:
print "Invalid input"
continue
c=c+1
num2=num+num2
num=raw_input("Enter a number.")
avg=num2/c
print num2, "\t", c, "\t", avg
You can solve the problem by moving the variable assignments into the try block. That way, the stuff you want to skip is automatically avoided when an exception is raised. Now there is no reason to continue and the next prompt will be displayed.
c=0
num2=0
num=raw_input("Enter a number.")
while num!=str("done"):
try:
num=float(num)
c=c+1
num2=num+num2
except:
print "Invalid input"
num=raw_input("Enter a number.")
avg=num2/c
print num2, "\t", c, "\t", avg
You can tighten this a bit further by removing the need to duplicate the prompt
c=0
num2=0
while True:
num=raw_input("Enter a number. ")
if num == "done":
break
try:
num2+=float(num)
c=c+1
except:
print "Invalid input"
avg=num2/c
print num2, "\t", c, "\t", avg
continue means return back to while, and as num never changes, you will be stuck in an infinite loop.
If you want to escape the loop when that exception occurs then use the term break instead.
# this function will not stop untill no exception trown in the try block , it will stop when no exception thrown and return the value
def get() :
i = 0
while (i == 0 ) :
try:
print("enter a digit str : ")
a = raw_input()
d = int(a)
except:
print 'Some error.... :( '
else:
print 'Everything OK'
i = 1
return d
print(get())
My error-handling code is not working. I'm trying to do following: if user enters any input other than 1, 2 or 3, then the user should get error message and the while-loop should start again.
However my code is not working. Any suggestion why?
def main():
print("")
while True:
try:
number=int(input())
if number==1:
print("hei")
if number==2:
print("bye")
if number==3:
print("hei bye")
else:
raise ValueError
except ValueError:
print("Please press 1 for hei, 2 for bye and 3 for hei bye")
main()
You can also use exception handling a bit more nicely here to handle this case, eg:
def main():
# use a dict, so we can lookup the int->message to print
outputs = {1: 'hei', 2: 'bye', 3: 'hei bye'}
print() # print a blank line for some reason
while True:
try:
number = int(input()) # take input and attempt conversion to int
print(outputs[number]) # attempt to take that int and print the related message
except ValueError: # handle where we couldn't make an int
print('You did not enter an integer')
except KeyError: # we got an int, but couldn't find a message
print('You entered an integer, but not, 1, 2 or 3')
else: # no exceptions occurred, so all's okay, we can break the `while` now
break
main()
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...