0

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

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0
in= 0
while True:
  try:
     in= int(input("Enter something: "))       
  except ValueError:
     print("Not an integer!")
     continue
  else:
     print("Yes an integer!")
     break 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.