Search code examples
pythonarea

I want to calculate area of different shape on python


The user input "circle 3.5" or "rectangle 3 5" or "trapezoid 3 5 7" (for the number decide by user) and output the area. Below is the code, but it can not run.

s=input("Input the shape and number:")
# for example,
# s="rect:5 3"
# s="cir:3.5"
#s="trapz:3 5 7"
cmd, para=s.split(:)
print(f"{cmd}->{para}")

if cmd == 'cir':
    r = float(para)
    print(f"area={r*r*3.14}")
elif cmd == 'rect':
    sw, sh = int(para.split())
    print(f"area={sw*sh}")
elif cmd == 'trapz':
    ul, bl, h = int(para.split())
    print(f"area={(ul+bl)*h/2}")
else:
    print("wrong input")

Thanks for the comments. I also try the other way to solve this question.The codes are:

s=input("Input the shape and number:").split()

if s[0]=="cir":
    r = float(s[1])
    print(f'area={r*r*math.pi}')
elif s[0]=="rect":
    sw, sh = int(s[1]), int(s[2])
    print(f"area={sw*sh}")
elif s[0]=="trapz":
    ul, bl, h = int(s[1]), int(s[2]), int(s[3])
    print(f'area={(ul+bl)*h/2}')
else:
    print('Wrong input!')

Solution

  • You have a few issues with your code. You are assigning a value to s after the user provides their input. I am assuming these were just for your own reference, so I commented them out.

    Since s.split() will convert your string into a list, you need to make sure you are assigning portions of your list to the right number of variables. You can't directly assign two variables to a three element list. So I have used s.split(':')[0], s.split(':')[1:] to get the first element of the list, then the remaining elements of the same list.

    Also you cannot apply int() to a list as Python won't do that much magic for you, so you need to use a list comprehension instead.

    s=input("Input the shape and number:")
    # s="rect:5:3"
    # s="cir:3.5"
    # s="trapz:3 5 7"
    cmd, para=s.split(':')[0], s.split(':')[1:]
    print(cmd,"->",para)
    
    if cmd=='cir':
        r = float(para[0])
        print(f"arear={r*r*3.14}")
    elif cmd=='rect':
        sw, sh =[int(x) for x in para]
        print(f"area={sw*sh}")
    elif cmd=='trapz':
        ul, bl, h = [int(x) for x in para]
        print(f"area={(ul+bl)*h/2}")
    else:
        print("wrong input")
    

    Sample outputs:

    Input the shape and number:rect:5:3
    rect -> ['5', '3']
    area=15
    
    Input the shape and number:cir:3.5
    cir -> ['3.5']
    arear=38.465
    
    Input the shape and number:trapz:3:5:7
    trapz -> ['3', '5', '7']
    area=28.0