Search code examples
python-3.xgeometryarea

How to get Python to work out the area of a circle given the radius by a user


Can I first say that I'm new to this whole Python and coding thing, anyway

This is my code:

pi = 3.14159265

choice = input ("Enter a number between 1-5:")
choice = int (choice)

if choice == 1:
    radius = (input ("Enter x:")
    area = ( radius ** 2 ) * pi
    print ("The Area of the circle is, " =area)

if choice == 2:
    radius = (input ("Enter x:")
    area = ( radius ** 2 ) * pi
    print ("The Area of the circle is, " =area)

if choice == 3:
    radius = (input ("Enter x:")
    area = ( radius ** 2 ) * pi
    print ("The Area of the circle is, " =area)

I keep getting a syntax error at each of the area = ( radius **2 ) * pi I was wondering why this keeps happening and what a solution would be to fix it, seeing that I'm very new to this, its probably quick and simple, I'm just being really stupid.

Anyway, thanks


Solution

  • The problem of your code is that you are reading the radius as a string and then you are trying to do mathematical operations on a string with an integer.

    Generally, it is good idea when you are reading an input from the user to cast the variable to the data type you wish to work with.

    This will fix your problem:

    import math
    pi = math.pi
    
    choice = input ("Enter a number between 1-5:")
    choice = int (choice)
    
    if choice == 1:
        radius = float(input ("Enter x:"))
        area = ( radius ** 2 ) * pi
        print ("The Area of the circle is, " + str(area))
    
    if choice == 2:
        radius = float(input ("Enter x:"))
        area = ( radius ** 2 ) * pi
        print ("The Area of the circle is, " + str(area))
    
    if choice == 3:
        radius = float(input ("Enter x:"))
        area = ( radius ** 2 ) * pi
        print ("The Area of the circle is, " + str(area))
    

    As you can see I changed a bit your print statement because the + operator should be used instead of the = and also you should cast again the numeric value into string using the str()

    I will also suggest to use the math.pi for your π constant instead of hard-coding the π value.

    Lastly, I can't understand the reason you are using 3 cases with exactly the same calculations, where you could have the same result with 3 lines of code.