-2

I'm new to programming and I'm trying to shorten a part of my program using user-defined functions, but I'm kinda lost. How do I shorten this or make it more efficient using user-defined functions?

import math


while True:
    print('#####################')
    print('# GEOMETRIC OBJECTS #')
    print('#####################')
    print('[1] Circle')
    print('[2] Triangle')
    print('[3] Rectangle')
    print('[4] Cone')
    print('[5] Triangular Pyramid')
    print('[6] Pyramid')
    print('[7] Exit')

    option = input('Option: ')

    if option == '7':
        print('You have exited.')
        exit()
        
    if option == '1': #Circle Geometric Object
        print('You have chosen circle.')
        print('')
        print('================')
        print('     CIRCLE     ')
        print('================')
        print('[1] Enter the length of the radius')
        print('[2] Area')
        print('[3] Circumference')
        print('[4] Back to main menu')

        optionCircle = input('Option: ')
        
        if optionCircle == '4':
            continue
        
        if optionCircle == '1':
            print('Enter the length of the radius.')

            Rad = float(input('> Radius: '))
            
        while True:
            
            print('')
            print('================')
            print('     CIRCLE     ')
            print('================')
            print('[1] Enter the length of the radius')
            print('[2] Area')
            print('[3] Circumference')
            print('[4] Back to main menu')
            
            optionRadius = input('Option: ')
        
            if optionRadius == '2':
                area = math.pi * Rad * Rad
                print('')
                print('> The area of the circle with a radius of ' + str(Rad) + ' is ' + str(area))
            
            elif optionRadius == '3':
                circum = 2 * math.pi * Rad
                print('')
                print('> The circumference of the circle with a radius of ' + str(Rad) + ' is ' + str(circum))
            
            else:
                break
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 2
    Please ask only one question per post. For the 2nd question: [Asking the user for input until they give a valid response](https://stackoverflow.com/q/23294658) – 001 Mar 10 '22 at 15:02
  • What have you researched before posting this question? – S3DEV Mar 10 '22 at 15:04
  • In general, adding functions makes code *less* efficient, as you are adding the overhead of managing the function call to whatever the function actually does. Usually, though, functions make the code more readable and maintainable, which is of greater value than making it run a little bit faster. – chepner Mar 10 '22 at 15:06
  • 1
    Saving a human a few minutes in understanding the code is almost always of higher value than saving the CPU a few clock cycles (or even a few trillion). Computers' time is very cheap compared to humans' time! – Samwise Mar 10 '22 at 15:16
  • You can make your code *shorter* by applying the ["Don't repeat yourself" (DRY)](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) principle of software development. It doesn't improve execution efficiency, but that's another topic and generally unimportant with respect to user-interface code. – martineau Mar 10 '22 at 15:41
  • Stackoverflow is to help solve specific, technical problems, not open-ended requests for code or advice. – martineau Mar 10 '22 at 15:43
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Mar 11 '22 at 03:14

1 Answers1

0

A very low-hanging example is this block of code, which you have repeated twice:

            print('')
            print('================')
            print('     CIRCLE     ')
            print('================')
            print('[1] Enter the length of the radius')
            print('[2] Area')
            print('[3] Circumference')
            print('[4] Back to main menu')
            
            optionRadius = input('Option: ')

You could turn this into a function:

def circle_menu() -> str:
    """Show the menu for a circle, return selection."""
    print('')
    print('================')
    print('     CIRCLE     ')
    print('================')
    print('[1] Enter the length of the radius')
    print('[2] Area')
    print('[3] Circumference')
    print('[4] Back to main menu')
            
    return input('Option: ')

and then replace the two places where you've copied and pasted the above code with:

    optionRadius = circle_menu()

Taking it a step further -- suppose you have a lot of menus like this and they all do sort of the same thing? You could define a generic menu function and define all your other menus in terms of that function:

def menu(title: str, options: list[str]) -> str:
    """Display a menu, return selection."""
    # Show the title with marquee around it.
    title_width = max(16, len(title))
    print('=' * title_width)
    print(title.center(title_width))
    print('=' * title_width)

    # Show all the options, numbered starting at 1.
    for i, option in enumerate(options, 1):
        print(f'[{i}] {option}')

    return input('Option: ')


def circle_menu() -> str:
    """Menu for a circle."""
    return menu(
        "CIRCLE", [
            'Enter the length of the radius',
            'Area',
            'Circumference',
            'Back to menu menu'
        ]
    )
Samwise
  • 68,105
  • 3
  • 30
  • 44